JSON objects returns undefined

2019-08-19 06:16发布

I'm returning a JSON object using a 3rd party API. When I print out the variable I get the following:

category: 
{
    "sys":
    {
        "id":"44uyBvGjFmsmoU6uqiiSOq",
        "revision":1,
        "type":"Entry",
        "locale":"en-US",
        "contentType":
        {
            "sys":
            {
                "id":"2V5tBa4wf6cuMSIu4McuUc",
                "type":"Link",
                "linkType":"ContentType"
            }
        },
        "createdAt":"2014-09-13T22:40:39.901Z",
        "updatedAt":"2014-09-13T22:40:39.901Z",
        "space":
        {
            "sys":
            {
                "id":"t667fybp3v46",
                "type":"Link",
                "linkType":"Space"
            }
        }
    },
    "fields":
    {
        "name":"birth control"
    }
}

But when I try and access the variables using the following, I keep on getting "Possibly unhandled TypeError: Cannot read property 'name' of undefined" :

if (o.fields.category)
{
    var str = JSON.stringify(o.fields.category, undefined, 2);
    console.log(str);

    var json_category = JSON.parse(str);
    // console.log("--------------Category for the resource: " + o.fields.category);
    $.each(json_category, function(index, object){
        alert(10);
        var category = {};
        // console.log("--------------Category for the resource: " + object.sys);
        category.id = object.sys.id;
        // console.log("--------------Category for the resource: " + object.fields.name);
        category.name = object.fields.name;
        // console.log("--------------Category for the resource: " + object.sys.updatedAt);
        category.updatedAt = object.sys.updatedAt;
        categories.push(category);
    });
 }

Any help is greatly appreciated.

1条回答
混吃等死
2楼-- · 2019-08-19 06:45

Changed my code to the following. Thanks to Pointy for providing the assistance, much appreciated.

if (o.fields.category)
{
    console.log(o.fields.category.fields.name);

    var category = {};
    category.id = o.fields.category.sys.id;
    category.name = o.fields.category.fields.name;
    category.updatedAt = o.fields.category.sys.updatedAt;
    categories.push(category);
}

record.categories = categories;
record.searchTags = search_tags;
records.push(record);
查看更多
登录 后发表回答