Solved: Create JSON key value pair from Question_Answer ta... - ServiceNow Community

Create JSON key value pair from Question_Answer table

Abhishek Pidwa
Kilo Guru

Hi All, 

I have a requirement where in I have to send the variables data to outside third party system. For this I have created a REST message and it is working absolutely fine. I have written an insert business rule which creates a JSON object and start adding stuff (sys_id etc.) . In order to retrieve the values of variables I had to query question_answer table but now I am unable to tie that variable question and answer as the key value pair. It is all dynamic and currently there are 40-50 variables.

find_real_file.png

Is there any way in Javascript to code it as name value pair. For e,g., {"question1": "answer1", "question2", "answer2" ...} ? Does anyone have any idea ? Appreciate your help. In the current context I am making a JSON object and then adding it . Any other way would also be fine if any.

 

Thanks,
Abhishek Pidwa

1 ACCEPTED SOLUTION

DScroggins
Kilo Sage

Hi Abhishek,

 

Please try the following:

 

var obj = {};
var gr = new GlideRecord('question_answer');
gr.addQuery('table_sys_id',current.sys_id);
gr.addQuery('value','!=','');
gr.query();
while(gr.next()){
  
  obj[gr.question.name.toString()] = gr.value.toString();
  
}

 

This will output an object with the name:value pairs based on the question_name:value.

 

Hope this helps.

 

--David

View solution in original post

4 REPLIES 4

rajendravunnam
Kilo Expert

Hi Abhishek,

I am not clear on the requirement. Do you want to send all variables and data as JSON ?

If so, try this:

var variableData=[];//Array


while(quesAnswerGR.next()){
variableData.push({"question":quesAnswerGR.question.name,"answer":quesAnswerGR.question.name});
}

gs.info(JSON.stringify(variableData));

Let me know if that helps.

Hi Rajendra, 

 

Thanks for replying but I wanted in a format which David just replied to. 

DScroggins
Kilo Sage

Hi Abhishek,

 

Please try the following:

 

var obj = {};
var gr = new GlideRecord('question_answer');
gr.addQuery('table_sys_id',current.sys_id);
gr.addQuery('value','!=','');
gr.query();
while(gr.next()){
  
  obj[gr.question.name.toString()] = gr.value.toString();
  
}

 

This will output an object with the name:value pairs based on the question_name:value.

 

Hope this helps.

 

--David

Awesome. Love this community reaching out so fast . Thanks David. That is the correct syntax I was looking for. Tried and tested. 🙂