
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
JSON PARSING: USE CASE AND SOLUTIONS
Everyday we are doing some development where we have a need to built JSON data and then parse it. I have put few methods with example were we can parse JSON easily, in this example we are focusing only on parsing data and not building it. I saw many post where people struggle to parse JSON and thought of putting everything together. This can be a useful article for people who are trying to develop scripting skills in ServiceNow.
Below are few basic and useful use case’s:
- Single Object in JSON.
- Nested Objects in one JSON Object.
- Single array from JSON object.
- Nested Array in JSON.
- How for loop can be used to parse through array.
Before we go to example, let’s try to understand difference between JSON.Stringify and JSON.Parse.
JSON.stringify will take JavaScript object and convert it into JSON string meaning it will serialize the data. so that JSON.Parse can accept it as an input.
JSON.Parse reads JSON.String and transform it into java-script object so that we can iterate through it and extract values from it.
1) Simple JSON Parsing:
Let’s try with basic and simple example first and then we will go deeper and try out some complex example.
Sample JSON:
{"firstName":"Ashutosh", "lastName":"Munot"}
Code:
var obj = {"firstName":"Ashutosh", "lastName":"Munot"};
var str = JSON.stringify(obj);
var parser = new JSONParser();
var result = parser.parse(str);
gs.print(‘First Name Attribute : ’+result.firstName);
Result:
***Script: First Name Attribute : Ashutosh
[0:00:00.003] Total Time
2) Parse Values from Nested objects in Single JSON:
Let’s increase complexity and use this case where we get data in multiple object and we need to parse and loop through it. Most of the Server in real time returns nested objects.
Sample JSON:
{
"id": "0001",
"type": "donut",
"name": "Cake",
"image":
{
"url": "images/0001.jpg",
"width": 200,
"height": 200
},
"thumbnail":
{
"url": "images/thumbnails/0001.jpg",
"width": 32,
"height": 32
}
}
Code:
var obj = {"id":"0001","type":"donut","name":"Cake","image":{"url":"images/0001.jpg","width":200,"height":200},"thumbnail":{"url":"images/thumbnails/0001.jpg","width":32,"height":32}};
var a = JSON.stringify(obj);
var parser = new JSONParser();
var parsed = parser.parse(a);
var img = parsed.image.width;
var thumb = parsed.thumbnail.width;
gs.log('Images Object attribute Width : '+img);
gs.log('Thumbnail Object attribute Width : '+thumb);
Result:
*** Script: Images Object attribute Width : 200
*** Script: Thumbnail Object attribute Width : 32
[0:00:00.004] Total Time
3) Parse Values from Single Array in JSON Object :
Lets increase the complexity and now we will try to parse Value from single array embedded into an JSON object. Taking below sample example where we will try to parse number key from object.
Sample JSON:
{
"arr": [
{
"parent": "",
"made_sla": "true",
"watch_list": "",
"u_when_needed": "2017-05-18 21:52:02",
"upon_reject": "cancel",
"sys_updated_on": "2017-01-30 22:51:35",
"u_what_needed": "legal1",
"approval_history": "",
"number": "NI002004",
"sys_updated_by": "admin",
"user_input": "",
"sys_created_on": "2017-01-30 22:51:35",
"state": "3"
}
]
}
Code:
Var obj={"arr":[{"parent":"","made_sla":"true","watch_list":"","u_when_needed":"2017-05-18 21:52:02","upon_reject":"cancel","sys_updated_on":"2017-01-30 22:51:35","u_what_needed":"legal1","approval_history":"","number":"NI002004","sys_updated_by":"admin","user_input":"","sys_created_on":"2017-01-30 22:51:35","state":"3"}]};
var str = JSON.stringify(obj);
var parser = new JSONParser();
var parsed = parser.parse(str);
var result = parsed.arr[0].number;
gs.print(‘Number : ’+result);
Result:
*** Script:Number :NI002004
[0:00:00.001] Total Time
4) Parse Value from Nested array in JSON Object:
Taking reference of the above example now we will see how to parse attribute from nested array embedded in JSON Object.
Sample JSON:
{
"name": "Peter parker",
"heroName": "Spiderman",
"friends": [{
"heroName": "Deadpool",
"skills": ["Martial artist", "Assassin"]
}, {
"heroName": "Hulk",
"skills": ["Superhuman Speed", "Superhuman Strength"]
}, {
"heroName": "Wolverine",
"skills": ["Retractable bone claws", "Superhuman senses"]
}]
}
Code:
Var abc = {"name":"Peter parker","heroName":"Spiderman","friends":[{"heroName":"Deadpool","skills":["Martial artist","Assassin"]},{"heroName":"Hulk","skills":["Superhuman Speed","Superhuman Strength"]},{"heroName":"Wolverine","skills":["Retractable bone claws","Superhuman senses"]}]};
var a = JSON.stringify(abc);
var parser = new JSONParser();
var parsed = parser.parse(a);
gs.print(‘Length of friends array : ’+parsed.friends.length); //This will give you length of friends array which is nested array.
gs.print(‘Friends Object : ’+parsed.friends[0]);//This will give you [Object object] for 0 index on friends array
gs.print(‘Skills Object from Friends of [0] index : ’+parsed.friends[0].skills);//This will give you values in skills array of 0 Index friends array. note skills is another array
gs.print(‘Skills value of index [0] : ’+parsed.friends[0].skills[0]);//This will give Martial artist from index 0 skills array from friends 0 index array.
Result:
*** Script: Length of friends array :3
*** Script: Friends Object : [object Object]
*** Script: Skills Object from Friends of [0] index : Martial artist,Assassin
*** Script: ‘Skills value of index [0] : ’Martial artist
[0:00:00.004] Total Time
5) How For loop can be used to parse through array:
In this example we will see how can we use for loop to parse through values in JSON and array.
Sample JSON:
Same JSON from above example
Code:
var abc = {"name":"Peter parker","heroName":"Spiderman","friends":[{"heroName":"Deadpool","skills":["Martial artist","Assassin"]},{"heroName":"Hulk","skills":["Superhuman Speed","Superhuman Strength"]},{"heroName":"Wolverine","skills":["Retractable bone claws","Superhuman senses"]}]};
gs.print(abc);
var a = JSON.stringify(abc);
var parser = new JSONParser();
var parsed = parser.parse(a);
var str = '';
var str1 = '';
for (var i in abc.friends) {
str += abc.friends[i].heroName + "<br/>";
for (var j in abc.friends[i].skills) {
str1 += abc.friends[i].skills[j] + "<br/>";
}
}
gs.print(str);
gs.print(str1);
Result:
2019-08-25T11:56:29.163Z: [object Object] |
2019-08-25T11:56:29.163Z: Deadpool |
2019-08-25T11:56:29.163Z: Martial artist |
Friends, this is very generic blog and will be useful in day to day coding for a learner or intermediate developer. Trying to help with this and will come up with new case's as i encountered them in practical implementation.
If you guys have any comments/ suggestions please leave it here and i will work on that. Bookmark this if you find it helpful.
Thanks,
Ashutosh Munot
MVP 2019
- 66,134 Views
- « Previous
-
- 1
- 2
- 3
- Next »
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.