简体   繁体   中英

How to access named JSON array with Javascript

I am getting a JSON array from an API. The returned data is written to console:

console.log(` data [${data}] `);

which prints:

{
    "aaData": [
        {                
            "create_date": "1/30/2023 07:43 AM",
            "description": "0800",
            "override_user_id": -1,
            "type": 1,
            "user_id": 32,
            "user_type": 0
        },
        {                
            "create_date": "1/30/2023 09:43 AM",
            "description": "1000",                
            "override_user_id": -1,                
            "type": 1,
            "user_id": 32,
            "user_type": 0
        },
        {                
            "create_date": "1/30/2023 11:43 AM",
            "description": "1200",                
            "override_user_id": -1,                
            "type": 1,
            "user_id": 32,
            "user_type": 0
        },
        {                
            "create_date": "1/30/2023 01:43 PM",
            "description": "1400",                
            "override_user_id": -1,
            "type": 1,
            "user_id": 32,
            "user_type": 0
        }
    ]
}

What I am expecting. But if I check the length ( expecting length of 4 )

console.log(`data [${data.length}] `);

I get:

data [607]

Which does not make sense to me. Furthermore, if I write the named array to console

console.log(` data [${data.aaData}] `);

I get:

data [undefined]

And, if I attempt to access the properties of the objects in the array I get undefined for each.

console.log( description = [${data.aaData[i].description}] );

I get

description = [undefined]

data is the variable returned from JQuery ajax call

success: function (data) {
...

Given that it prints directly to console without having to stringfy it, the returned data should be the string version of the json object. However, if I apply

console.log(` data[${JSON.parse(data)}] `);

displays

data [undefined]

What am I not understanding here?

It looks like data is a string so data.length will return the length of the string which is 607 in your case. To convert the data to JSON, add dataType: 'json' to the $.ajax() options like so:

$.ajax({
    ...
    dataType: 'json',
    success: function (data) {
        console.log(data)
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM