Parsing JSON with Square Brackets Embedded []

Jamison Cote2
Mega Expert

The following JSON object is 'un-parsable' using the classical decoding methods.

For example:

var obj = {
    "startAt":0, 
    "maxResults":1048576,
    "total": 1, 
    "comments":
    [{
        "name1": "value1",
        "name2": "value2",
    }]
};

But I noticed that when the [] square brackets are removed from the payload, then the JSON methods work as expected:

var obj = {
    "startAt":0, 
    "maxResults":1048576,
    "total": 1, 
    "comments":
    {
        "name1": "value1",
        "name2": "value2",
    }
};

The below works as expected on the second JSON object, but fails on the first.

var parser = new JSON();
var str = parser.encode(obj);
gs.print(str); // Prints JSON payload
gs.print(obj.comments.name1); // Prints value

 

 

1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Jamison,

For the first json the object is not proper. there is an extra comma so it is not getting parsed i.e. after value2

also it is having an array so you need to use comments[0] instead of comments in first json

the second json object doesn't have an array so it is easily parseable

sample script below for first json

var str = '{"startAt":0,"maxResults":1048576,"total":1,"comments":[{"name1":"value1","name2":"value2"}]}';

var jsonparser = new JSONParser();

var parsedData = jsonparser.parse(str);

gs.print(parsedData.comments[0].name1); // Prints value

Mark Correct if this solves your issue and also mark Helpful if you find my response worthy based on the impact.
Thanks
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

View solution in original post

2 REPLIES 2

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Jamison,

For the first json the object is not proper. there is an extra comma so it is not getting parsed i.e. after value2

also it is having an array so you need to use comments[0] instead of comments in first json

the second json object doesn't have an array so it is easily parseable

sample script below for first json

var str = '{"startAt":0,"maxResults":1048576,"total":1,"comments":[{"name1":"value1","name2":"value2"}]}';

var jsonparser = new JSONParser();

var parsedData = jsonparser.parse(str);

gs.print(parsedData.comments[0].name1); // Prints value

Mark Correct if this solves your issue and also mark Helpful if you find my response worthy based on the impact.
Thanks
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Hi Ankur,

Could you please help me to extract data in case if the field type is multi select? Following is the JSON body. I want to fetch all the 'value' from it. 

find_real_file.png