search

Home  >  Q&A  >  body text

javascript - The string value parsed by JSON.stringify is undefined

msg is an object

var descriptionMsg = JSON.stringify(msg);
descriptionMsg is printed as: {"title":"aaaaaaa","image":"xxxxxx.png","content":"vvvvvv"} is a string

But
document.write(descriptionMsg.title);or document.write(descriptionMsg['title']);

are all printed as: undefined

why is that?

仅有的幸福仅有的幸福2858 days ago948

reply all(6)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-05-18 10:59:47

    descriptionMsg is already a string, so it is naturally impossible to have descriptionMsg.title;
    console.log(msg.title) Try?

    reply
    0
  • 怪我咯

    怪我咯2017-05-18 10:59:47

    document.write(JSON.parse(descriptionMsg).title)

    reply
    0
  • 黄舟

    黄舟2017-05-18 10:59:47

    JSON.stringify()Used to parse a string from an object

    reply
    0
  • PHP中文网

    PHP中文网2017-05-18 10:59:47

    JSON.stringify(obj) passes in a native object and returns a string. Of course, you cannot get the value by using JSON.stringify(obj).key, so it is undefined. If you want to get the value, you can Directly use the unconverted native object obj.key, or JSON.parse(JSON.stringify(obj)).key to parse the converted json string into a native object.

    reply
    0
  • 阿神

    阿神2017-05-18 10:59:47

    descriptionMsg is a string, not an object in json format. You need to use JSON.parse to convert it. JSON.stringify converts objects into strings, but you used it the other way around.

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-18 10:59:47

    descriptionMsg is a string, so you need to convert the string into an object first, and then access the properties of the object:
    document.write(JSON.parse(descriptionMsg).title)

    reply
    0
  • Cancelreply