[英]Unable to access a key value from a json
I have a json as below 我有一个JSON如下
var object = {200x200: "url1", 400x400: "url2", 800x800: "url3"};
I stringified the object and tried to acccess "200x200". 我对该对象进行了字符串化处理,并尝试添加“ 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 ? 还有其他方法可以从此对象访问url1吗?
Because you json object is wrong format: 因为您的json对象格式错误:
Wrap your keys in quotes, like this: https://codepen.io/creativedev/pen/LrBOmG 将您的密钥括在引号中,如下所示: 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 https://developer.mozilla.org/zh-CN/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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.