Not able to dot or bracket notation walk nested hyphenated JSON objects

Enea1
Tera Expert

Hello,

 

I am pulling JSON data from a third party API. The data object (although truncated to only show one), looks like this:

 

{
    "data": [
        {
            {
            "id": "625",
            "type": "projects",
            "attributes": {
                "object-type": "Project",
                "team-id": 2,
                "team": {
                    "id": 2,
                    "object-type": "Team",
                    "name": "Test team name",
                    "created-at": "2019-12-17T05:11:41.711Z",
                    "updated-at": "2022-12-12T20:54:11.504Z"
                },
                "purchasing-agency-id": 77,
                "purchasing-agency": {
                    "id": 77,
                    "team-id": 2,
                    "name": "Test Agency Name",
                    "twitter-link": "https://twitter.com/fsdfsdf",
                    "facebook-link": "https://www.facebook.com/sdfsdfsdfsdf",
                    "youtube-link": "https://www.youtube.com/cfdsfsfd",
                    "email": "mailto:webmaster@sdfdsfsfsfsdfs.com",
                    "created-at": "2020-07-24T00:31:20.363Z",
                    "updated-at": "2022-09-01T23:57:21.694Z"
                },
                "name": "Test software name",
                "status": "archived",
                "published-at": null,
                "archived-at": "2021-01-26T18:56:27.496Z",
                "procurement-official-id": 214,
                "procurement-official": {
                    "id": 214,
                    "object-type": "Membership",
                    "team-id": 2,
                    "user-id": 154,
                    "user": {
                        "id": 154,
                        "first-name": "Jim",
                        "last-name": "Hanson",
                        "email": "jim.hanson@yahoo.com",
                    }
        }
    ]
}

 

 
 
I am trying to set up a scheduled job script that will pull this data and update records on my instance every day.
 
To test the data, I am trying to access for example, the first name of the individual. 
After setting the following variables:

 

var response = r.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();
var parser = new JSONParser();
var parsed = parser.parse(responseBody);

 

 
This works and I get a name showing in the logs:

 

​gs.log(parsed.data[1]['attributes']['procurement-official']['user']['first-name']


however, the moment I put it inside any sort of loop, it breaks down and no longer returns what I need. The log is just filled with system logs that are difficult to parse through but they don't even seem related.

 


I have tried with and without quotation marks along with every combination of dot/bracket walking possible:

 

for (var key in parsed.data) {
       gs.info("Key is: " + key + " and value is: " + parsed.data[key]['attributes']['procurement-official']['user']['first-name']);
}

 

...

 

​for (i = 0; i < parsed.data.length; i++) {
gs.log(parsed.data[i]['attributes']['procurement-official']['user']['first-name']);
}


For some reason, if I log everything up to

['user']

 I do get: 

 

 

2022-12-15 11:57:01
InformationKey is: 279 and value is: [object Object]*** ScriptLog Entry

 

So it's picking up that an object exists.. it just wont let me go into the last key of that object.

Again, outside of the loop and targeting one object, the notation seems to work.

 

Any ideas what I'm doing wrong with the loop?

 

Thank you in advance.

1 ACCEPTED SOLUTION

Enea1
Tera Expert

I think I solved the issue. You cannot iterate through null values at all. The loop breaks the moment it hits a null object. You HAVE to check for null and skip the iteration using "continue". You also have to check for the string value of "null" and not just the keyword null.

This is working and providing me with the first name of all the users it iterates on:

 

 

 

try {
    var r = new sn_ws.RESTMessageV2('STP CI Solicitation', 'Default GET');

    var response = r.execute();
    var responseBody = response.getBody();
    var httpStatus = response.getStatusCode();
    var parser = new JSONParser();
    var parsed = parser.parse(responseBody);

    gs.info(httpStatus);

    for (i = 0; i <= 10; i++) {
        var userVariable = JSON.stringify((parsed.data[i]['attributes']['procurement-official']['user']));
        if (userVariable != "null") {
            gs.info(JSON.stringify((parsed.data[i]['attributes']['procurement-official']['user']['first-name'])));
        } else {
            continue;
        }

    }

} catch (ex) {
    var message = ex.message;
    gs.error("This is the ex error message" + message);
}

 

 

 

 Thank you all for the help.

View solution in original post

17 REPLIES 17

Yes that is what I was asking for -- this seems to be an invalid JSON object structure. For some reason there is an unnecessary opening curly bracket within the data array property.

 

Like if you go to jsonformatter.org and copy and paste the snippet you just shared, it will throw an error:

chrisperry_0-1671145563136.png

But if you delete the opening curly bracket from line 3, then it becomes a valid JSON object and the json formatter doesn't return any error:

chrisperry_1-1671145645520.png

 

 

 

If this answer is helpful please mark correct and helpful!

Regards,
Chris Perry

That was probably a mistake of mine when removing all but one of the array objects.

I popped the entire return object into that formatter and I am not getting any errors when it is whole. Not to mention I definitely can navigate to a specific index and have it print out completely. It's just the loop that wont work.

Hmm... okay, if you're able to share the entire, valid JSON snippet that would be helpful to pinpoint the issue.

 

For what it's worth, I just tested the code I provided you against the valid JSON object snippet with the unnecessary opening curly bracket from line 3 removed, plus I added a second dummy object to the data array property, and it worked like a charm:

 

 

var jsonObj = {
"data": [
    {
            "id": "1275",
            "type": "projects",
            "attributes": {
                "object-type": "Project",
                "team-id": 2,
                "team": {
                    "id": 2,
                    "object-type": "Team",
                    "name": "Test name",
                    "created-at": "2019-12-17T05:11:41.711Z",
                    "updated-at": "2022-12-12T20:54:11.504Z"
                },
                "purchasing-agency-id": 203,
                "purchasing-agency": {
                    "id": 203,
                    "team-id": 2,
                    "name": "Test Name of Agency",
                    "twitter-link": "https://twitter.com/dsfsdfsdf",
                    "facebook-link": null,
                    "youtube-link": "https://www.youtube.com/dsfsdfsdf",
                    "email": "mailto:info@dfsffsd.com",
                    "created-at": "2020-07-24T00:31:21.490Z",
                    "updated-at": "2022-09-01T23:57:23.015Z"
                },
                "name": "Name of project",
                "status": "addendum",
                "published-at": null,
                "archived-at": null,
                "procurement-official-id": 212,
                "procurement-official": {
                    "id": 212,
                    "object-type": "Membership",
                    "team-id": 2,
                    "user-id": 135,
                    "user": {
                        "id": 135,
                        "first-name": "John",
                        "last-name": "Doe",
                        "email": "thebatman@yahoo.com",
                        "procurement-official-id": null,
                        "role": null
                    },
                    "created-at": "2020-09-17T01:02:56.140Z",
                    "updated-at": "2022-11-04T00:37:25.576Z"
                },
                "published-by-id": null,
                "published-by": null,
                "archived-by-id": null,
                "archived-by": null,
                "solicitations-type-id": 3,
                "solicitations-type": {
                    "id": 3,
                    "object-type": "Solicitations::Type",
                    "team-id": 2,
                    "name": "Request For Offer",
                    "abbreviation": "RFO",
                    "show-lpa-options": true,
                    "created-at": "2020-01-17T17:34:12.668Z",
                    "updated-at": "2022-09-01T23:02:31.488Z"
                },
                "solicitations-vehicle-id": 3,
                "solicitations-vehicle": {
                    "id": 3,
                    "object-type": "Solicitations::Vehicle",
                    "team-id": 2,
                    "name": "California Multiple Award Schedule",
                    "abbreviation": "CMAS",
                    "created-at": "2020-01-17T17:38:24.751Z",
                    "updated-at": "2022-12-12T20:28:32.127Z"
                },
                "purchase-estimate": "250000.0",
                "solicitations-purchase-class-id": 4,
                "solicitations-purchase-class": {
                    "id": 4,
                    "object-type": "Solicitations::PurchaseClass",
                    "team-id": 2,
                    "name": "IT Consulting Services",
                    "created-at": "2020-02-08T21:31:24.585Z",
                    "updated-at": "2022-12-12T20:53:49.791Z"
                },
                "master-document-id": 30867,
                "solicitations-category-ids": [
                    5
                ],
                "solicitations-categories": [
                    {
                        "id": 5,
                        "object-type": "Solicitations::Category",
                        "team-id": 2,
                        "name": "Consulting",
                        "created-at": "2020-03-03T20:59:56.895Z",
                        "updated-at": "2020-03-03T20:59:56.895Z"
                    }
                ],
                "solicitations-subcategory-ids": [],
                "solicitations-subcategories": [],
                "external-id": "",
                "created-at": "2022-07-05T21:09:04.900Z",
                "updated-at": "2022-12-12T17:51:52.719Z"
            }
        },
        {
            "id": "1275",
            "type": "projects",
            "attributes": {
                "object-type": "Project",
                "team-id": 2,
                "team": {
                    "id": 2,
                    "object-type": "Team",
                    "name": "Test name",
                    "created-at": "2019-12-17T05:11:41.711Z",
                    "updated-at": "2022-12-12T20:54:11.504Z"
                },
                "purchasing-agency-id": 203,
                "purchasing-agency": {
                    "id": 203,
                    "team-id": 2,
                    "name": "Test Name of Agency",
                    "twitter-link": "https://twitter.com/dsfsdfsdf",
                    "facebook-link": null,
                    "youtube-link": "https://www.youtube.com/dsfsdfsdf",
                    "email": "mailto:info@dfsffsd.com",
                    "created-at": "2020-07-24T00:31:21.490Z",
                    "updated-at": "2022-09-01T23:57:23.015Z"
                },
                "name": "Name of project",
                "status": "addendum",
                "published-at": null,
                "archived-at": null,
                "procurement-official-id": 212,
                "procurement-official": {
                    "id": 212,
                    "object-type": "Membership",
                    "team-id": 2,
                    "user-id": 135,
                    "user": {
                        "id": 135,
                        "first-name": "Bob",
                        "last-name": "Doe",
                        "email": "thebatman@yahoo.com",
                        "procurement-official-id": null,
                        "role": null
                    },
                    "created-at": "2020-09-17T01:02:56.140Z",
                    "updated-at": "2022-11-04T00:37:25.576Z"
                },
                "published-by-id": null,
                "published-by": null,
                "archived-by-id": null,
                "archived-by": null,
                "solicitations-type-id": 3,
                "solicitations-type": {
                    "id": 3,
                    "object-type": "Solicitations::Type",
                    "team-id": 2,
                    "name": "Request For Offer",
                    "abbreviation": "RFO",
                    "show-lpa-options": true,
                    "created-at": "2020-01-17T17:34:12.668Z",
                    "updated-at": "2022-09-01T23:02:31.488Z"
                },
                "solicitations-vehicle-id": 3,
                "solicitations-vehicle": {
                    "id": 3,
                    "object-type": "Solicitations::Vehicle",
                    "team-id": 2,
                    "name": "California Multiple Award Schedule",
                    "abbreviation": "CMAS",
                    "created-at": "2020-01-17T17:38:24.751Z",
                    "updated-at": "2022-12-12T20:28:32.127Z"
                },
                "purchase-estimate": "250000.0",
                "solicitations-purchase-class-id": 4,
                "solicitations-purchase-class": {
                    "id": 4,
                    "object-type": "Solicitations::PurchaseClass",
                    "team-id": 2,
                    "name": "IT Consulting Services",
                    "created-at": "2020-02-08T21:31:24.585Z",
                    "updated-at": "2022-12-12T20:53:49.791Z"
                },
                "master-document-id": 30867,
                "solicitations-category-ids": [
                    5
                ],
                "solicitations-categories": [
                    {
                        "id": 5,
                        "object-type": "Solicitations::Category",
                        "team-id": 2,
                        "name": "Consulting",
                        "created-at": "2020-03-03T20:59:56.895Z",
                        "updated-at": "2020-03-03T20:59:56.895Z"
                    }
                ],
                "solicitations-subcategory-ids": [],
                "solicitations-subcategories": [],
                "external-id": "",
                "created-at": "2022-07-05T21:09:04.900Z",
                "updated-at": "2022-12-12T17:51:52.719Z"
            }
        }
    ]
};

var dataArr = jsonObj.data;
for (var i = 0; i < dataArr.length; i++) {
gs.info(String(dataArr[i]['attributes']['procurement-official']['user']['first-name']));
}

 

 

Output:

chrisperry_0-1671147737343.png

If this answer is helpful please mark correct and helpful!

Regards,
Chris Perry

Enea1
Tera Expert

Hi Chris, thank you kindly for your response, although it did not work for me unfortunately. This new way won't even print the single value when I pull it out of the loop unfortunately.

Enea1
Tera Expert

This is making little sense to me. 

If I execute this scheduled job:

 

try {
    var r = new sn_ws.RESTMessageV2('STP CI Solicitation', 'Default GET');
    var response = r.execute();
    var responseBody = response.getBody();
    var httpStatus = response.getStatusCode();
    var parser = new JSONParser();
    var parsed = parser.parse(responseBody);
    gs.info(httpStatus);
    for (i = 0; i <= 4; i++) {
        var userVariable = JSON.stringify((parsed.data[i]['attributes']['procurement-official']['user']));
        gs.info("Print the user name " + userVariable);
    }
} catch (ex) {
    var message = ex.message;
    gs.info("this is the error you have been waiting for");
}

 

I get the following logged:

objects.png

 

You can clearly see there are 5 records returning correctly as objects.

But if I try to print this instead:

 

try {
    var r = new sn_ws.RESTMessageV2('STP CI Solicitation', 'Default GET');
    var response = r.execute();
    var responseBody = response.getBody();
    var httpStatus = response.getStatusCode();
    var parser = new JSONParser();
    var parsed = parser.parse(responseBody);
    gs.info(httpStatus);
    for (i = 0; i <= 4; i++) {
        var userVariable = JSON.stringify((parsed.data[i]['attributes']['procurement-official']['user']['first-name']));
        gs.info("Print the user name " + userVariable);
    }
} catch (ex) {
    var message = ex.message;
    gs.info("this is the error you have been waiting for");
}

 

which is exactly the same apart from the addition of the last nested key I'm trying to dive into "first-name", I get the following:

objects error.png

So my error is being caught. 

Someone please help me understand why I cannot iterate into the last object.

Stranger yet, when I try to print it this way:

 

try {
    var r = new sn_ws.RESTMessageV2('STP CI Solicitation', 'Default GET');
    var response = r.execute();
    var responseBody = response.getBody();
    var httpStatus = response.getStatusCode();
    var parser = new JSONParser();
    var parsed = parser.parse(responseBody);
    gs.info(httpStatus);
    for (i = 0; i <= 4; i++) {
        var userVariable = JSON.stringify((parsed.data[i]['attributes']['procurement-official']['user']));
        gs.info("Print the user name " + userVariable['first-name']);
    }
} catch (ex) {
    var message = ex.message;
    gs.info("this is the error you have been waiting for");
}

 

In that I add the key to the variable, I get the following: 

objects error 2.png

"undefined".
Why, if I am able to walk all the way to the user object including hyphenated "procurement-officer" can I not grab the last key?