Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Iterate Through Array in JSON Object

suttonj
Kilo Explorer

I am having problems with pulling out the data in the "addresses" array. Below is what my json looks like:

 

"{\"processing_time_milliseconds\": 714, \"addresses\": [{\"address1\": \"7899 hello road\", \"address2\": \"\", \"city\": \"Neverland\", \"state_or_province\": \"CA\", \"postal_code\": \"23487\", \"postal_code_extension\": \"3352\", \"county\": \"Land\", \"country_code\": \"US\", \"latitude\": \"22.43456\", \"longitude\": \"-45.67977\"}]}"

 

And here is the snipped of my code:

var responseBody = response.getBody();
var httpStatus = response.getStatusCode();

var parser = new JSONParser();
var parsed = parser.parse(responseBody);


for (i = 0; i < parsed.addresses.length; i++) {
    gs.print(parsed.addresses[i].address1);
 }

 

It is never making into my for loop because the length is returning undefined. I am wanting to be able to parse out each individual piece of data to store other places (address, state, city, zip, etc.). Am I missing something here as to why this is not working?

 

Thanks!

10 REPLIES 10

If you are using a MID server, can you check, what you are getting in ECC queue?

And try below code. I hope you have a execute() function before this script

var httpStatus = response.getStatusCode();

var parsed = JSON.parse(response.getBody());


for (i = 0; i < parsed.addresses.length; i++) {
    gs.print(parsed.addresses[i].address1);
 }

Please mark this response as correct or helpful if it assisted you with your question.

Hi - I am not using a midserver and that is not working for me either

Hi suttonj,
The issue might be that addresses[] only contains one position based on your payload, so you can't loop on it and need to make explicit calls. Try something like this:

var txt = "{\"processing_time_milliseconds\": 714, \"addresses\": [{\"address1\": \"7899 hello road\", \"address2\": \"\", \"city\": \"Neverland\", \"state_or_province\": \"CA\", \"postal_code\": \"23487\", \"postal_code_extension\": \"3352\", \"county\": \"Land\", \"country_code\": \"US\", \"latitude\": \"22.43456\", \"longitude\": \"-45.67977\"}]}"

var parsed = JSON.parse(txt);
var value = parsed.addresses[0].city;
//returns 'Neverland'

 

What does it print 

 

var httpStatus = response.getStatusCode();
gs.print('+++++++response is+++++++++'+response.getBody());
var parsed = JSON.parse(response.getBody());


for (i = 0; i < parsed.addresses.length; i++) {
    gs.print(parsed.addresses[i].address1);
 }

Please mark this response as correct or helpful if it assisted you with your question.

It gives me back undefined in the for