简体   繁体   中英

JSON can't access data returns undefined

I have the following code,

var json = [
    {
        "name": "Fashion Forward",
        "good": {
            "doors" : {
                "name1" : "ff_good_doors_1.jpg",
                "name2" : "ff_good_doors_2.jpg",
                "name3" : "ff_good_doors_3.jpg"
            }
        },
        "better": {

        },
        "best": {

        }

    }
]

I would expect to be able get data out by doing something like,

json.name which I would expect to contain "Fashion Forward" - however I get undefined return, but if I console.log(json) I can see that it is an object.

Where am I going wrong?

json是数组的名称,您可以像这样使用json[0].name;

Why you use Array ? if you want to access members like what you already said :

I would expect to be able get data out by doing something like,

json.name which I would expect to contain "Fashion Forward" - however I get undefined return, but if I console.log(json) I can see that it is an object .

Where am I going wrong?

use this code and remove array:

var json =    {
   "name": "Fashion Forward",
   "good": {
       "doors" : {
           "name1" : "ff_good_doors_1.jpg",
           "name2" : "ff_good_doors_2.jpg",
           "name3" : "ff_good_doors_3.jpg"
       }
   },
   "better": {},
   "best": {}
}

Now you may use json.name

As it looks from your code, json is an array of single item. Try this

json[0].name

Let me know if it works for you.

the json variable is an array . to get the first object you need to select it like this json[0] and then you can access the the name property like this

var name = json[0].name;

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-2024 STACKOOM.COM