简体   繁体   English

无法访问json对象属性返回undefined

[英]cannot access json object property returns undefined

I am accessing a key from json object but it returns undefined 我从json对象访问一个键,但它返回undefined

{"body":"Hi","date":"2016-07-29 07:43:00"}

var a = JSON.parse(JSON.stringify(r.txt));
console.log(a.body)

//undefined

value of r is r的值是

{
  username: '1',
  txt: '{"body":"Hi","date":"2016-07-29 07:43:00"}',
 }

I have tried using stringify and then parse to json but still return undefined. 我已经尝试使用stringify,然后解析为json但仍然返回undefined。

You've to parse your json like this. 你要像这样解析你的json Ensure that your whatever input you're giving to JSON.parse, it should be a string. 确保你给JSON.parse的任何输入,它应该是一个字符串。

You can run the below snippet to ensure that it's working and giving output Hi . 您可以运行以下代码段以确保它正常工作并输出Hi

 var json = '{"body":"Hi","date":"2016-07-29 07:43:00"}'; var a = JSON.parse(json); document.write(a.body); 

In your code stringified result would be "\\"{\\"body\\":\\"Hi\\",\\"date\\":\\"2016-07-29 07:43:00\\"}\\"" (which is valid string representation in JSON), parsing it would again provide the string as result not the object. 在您的代码中,字符串化的结果将是"\\"{\\"body\\":\\"Hi\\",\\"date\\":\\"2016-07-29 07:43:00\\"}\\"" (这是JSON中的有效字符串表示),解析它将再次提供字符串作为结果而不是对象。 When you were trying to get body property of string which will be undefined since there is no property like body for a string. 当你试图获取字符串的body属性时,由于字符串没有像body这样的属性,因此它将是undefined

So there is no need to stringify a JSON string again just avoiding the stringify method would make it work. 因此,不需要再次对JSON字符串进行字符串化,只是避免使用stringify方法使其工作。

 var r = { username: '1', txt: '{"body":"Hi","date":"2016-07-29 07:43:00"}', }; // parse the JSON string and get the object var a = JSON.parse(r.txt); console.log(a.body) 

You have to remove single quote in r.txt and it should work 你必须删除r.txt中的单引号,它应该工作

Here is the code I updated : 这是我更新的代码:

var r = {
  username: '1',
  txt: {"body":"Hi","date":"2016-07-29 07:43:00"},
 };

var a = JSON.parse(JSON.stringify(r.txt));
console.log(a.body)

If r.txt is string you only need parse it. 如果r.txtstring ,则只需要解析它。 If it's an object , you will convert it to string by stringify then parse it 如果它是一个object ,你将通过stringify将其转换为字符串,然后parse

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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