How to fetch the JSON elements value - any function available OOB

ashwani_eshoppi
Kilo Expert

By using the below code, i am able to get the exact JSON request body which is getting passed from another application

var json = new JSON().encode(request.body.data)

{  

  "code":200,

  "params":{},

  "data":{  

  "element1":" 111",

  "element2":"234",

  "element3":"567",

  "element4":"2015-01-18",

          }

}

I need to fetch one of the elements value (element2) from within this JSON request body and further use that for updating a record's field.

How can i fetch this , is there any function available OOB. In JSON Script include, i cannot see any function to accept a key .which returns a value.

I even tried using dot walking (like json.data.element1, also json.element1,) but it gives me undefined error.

15 REPLIES 15

Bhargava4
Mega Expert

Hi ,



how you are get the JSON value like inbound email or REST API



for Example you get the JSON   from email use below code :



var parser = new JSONParser();


var json_alert = parser.parse(email.body_text);


var xxx = json_alert.data;


for(var x=0; x<json_alert.data.length; x++){


var gr = new GlideRecord(table name)


gr .initialize();


gr.field name = json_alert.data[x].element2;


gr.field name = json_alert.data[x].element1;


gr.insert()


}


andrew_lawlor
Giga Expert

Once you've decoded the JSON back into a native object, you can access its properties with their names as keys.



So:



var json = new JSON().decode(request.body.data);



var value = json[key];



You can iterate through the properties using a for in loop:



for (var key in json) {


var value = json[key];


// Do something.


}


Bhargava4
Mega Expert

Hi,



good question ?


why i am using loop for multiple records .here you see single record so?


for example you are getting multiple responds in JSON output   it works . i am not sure



its works good for me ,



Thanks


Ram  


You're not looping through multiple records; you're iterating through the properties of the object you've stored in your variable called 'json'.


Bhargava4
Mega Expert

I think The below code working good , you are find any thing please let me know i will correct it Andrew .


var parser = new JSONParser();


var json_alert = parser.parse(email.body_text);


for(var x=0; x<json_alert.data.length; x++){


var gr = new GlideRecord(table name)


gr .initialize();


gr.field name = json_alert.data[x].element2;


gr.field name = json_alert.data[x].element1;


gr.insert()


}