简体   繁体   中英

Unable to access a key value from a json

I have a json as below

var object = {200x200: "url1", 400x400: "url2", 800x800: "url3"};

I stringified the object and tried to acccess "200x200". But its throwing

undefined

object = JSON.stringify(object);
//object = {"200x200": "url1", "400x400": "url2", "800x800": "url3"};

I tried to access like this

object['200x200'] // got undefined

Any other way to access the url1 from this object ?

Because you json object is wrong format:

Wrap your keys in quotes, like this: https://codepen.io/creativedev/pen/LrBOmG

var object = {'200x200': "url1",'400x400': "url2", '800x800': "url3"};

Then check:

console.log(object['200x200']);

you will get output

you should change you object to

var object = {'200x200': "url1", '400x400': "url2", '800x800': "url3"};

object['200x200'] // 'url1'

Once you stringify it, it's a string. You have to parse it back into an object.

var newObject = JSON.parse(object);
console.log(object[200x200];

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

You can parse it:

object = JSON.parse(object);

then access the key:

let url1 = object['200x200']

No idea why you would stringify it in the first place though!

let jsonObject = JSON.stringify(object);
// instead of:
let url1 = JSON.parse(JSON.stringify(object))['200x200']

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