how to get exact string value without modifications in Javascript

Vineela1
Tera Contributor

Hi Team,

I have a requirement, from Third party client , I receive JSON format value. I want to copy to ServiceNow table which field type is string. then converting to JSON and copy to corresponding table.

Here I am facing challenge while copying JSON format value to string variable. It is getting changed the format.

 

Like example :

I will get JSON value from Third party as:

 

{"budget":"value","location":"value","jobid":"value"}

 

while getting to string value. It is like below format:

{budget=value,location=value,jobid=value}

 

Then I am unable to convert back to JSON. Please suggest do we have option to create a JSON variable in ServiceNow to store the json format value as it is.

 

Thanks and Regards,

 

Vineela

 

1 ACCEPTED SOLUTION

Store this value in the short description of any incident record.

{budget=value,location=value,plbs=value,u_custom_field1={loc={a=b,c={d=e}},plbs=value}}

 

Then use below in background script.

var grInc = new GlideRecord('incident');
grInc.get('<sys_id_of_that_incident_in_which_you_stored_above_value>');

var str = grInc.short_description.replace(/=/g, '":"');
str = str.replace(/,/g, '","');
str = str.replace(/{/g, '{"');
str = str.replace(/"{/g, '{');
str = str.replace(/}/g, '"}');
str = str.replace(/}"/g, '}');

gs.print(str);
var obj = JSON.parse(str);

printJSON(obj);

function printJSON(obj){
        for(var key in obj){
                if(typeof obj[key] == 'object'){
                        gs.print(key);
                        printJSON(obj[key]);
                }else{
                        gs.print(key + ': ' + obj[key])
                }
        }
}

 

View solution in original post

16 REPLIES 16

Hi Mohith,

 

Please suggest how can I make it to stringify method before inserting to ServiceNow table string field.

 

Also will that works if I have json structure like this for name/value pair field?.

{

"budget":"value",

"location":"value",

"plbs":"value",

"u_custom_field1":

 {

    "loc": "value",

    "plbs":"value"

}

}

@Vineela1 So the above format might work for name value pair field its just that there are nested JSON's in your master JSON .you can give a try 

and to answer how to stringify you just need to use JSON.stringify('your JSON');

Hi Mohith,

can you please help me on code how to stringify before string value getting inserted in table.

Can I use before Business rule? Please help with code

Please suggest .

@Vineela1 yes you can use the before insert BR fort this and just try this script mentioned below 

 

current.your_String_field_name = JSON.stringify('your JSON');

 

Hope this helps 

Hi Mohith,

But how will I get JSON?

can I give same field name ?