带或不带引号的JSON对象 [英] JSON Object With or Without Quotes

查看:125
本文介绍了带或不带引号的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习JSON,我了解到任何带有双引号键的javascript对象都被视为JSON对象。

I am trying to learn JSON, i learned that any javascript object with the key in double quotes are considered as JSON object.

我构建了这个对象

var jstr1 = {"mykey": "my value"};

但是当我尝试使用JSON.parse(jstr1)解析时,我收到以下错误。请参阅屏幕截图。

But when i try to parse using JSON.parse(jstr1), i got the following error. see the screenshot.

但是当我尝试解析这个

var jstr = '{"mykey": "my value"}';,

我获得了成功,请参见截图。我对此感到困惑。请解释我为什么会这样。两种形式之间有什么区别。

i got the success, see the screenshot. i got confused with this. Please explain me why this happens. what is the difference between the two forms.

当我从任何服务获得JSON作为响应时,它的外观如何,是否会以 jstr jstr1

And when i got JSON as a response from any services, how it would look like, whether it will be in form of jstr or jstr1

提前感谢您的任何帮助。

thanks in advance for any help.

推荐答案

您正在创建一个Javascript 对象。如果你想要一个JSON字符串,请使用 JSON.stringify

You are creating a Javascript Object. If you want a JSON-string from it, use JSON.stringify.

所以

var myObj = {mykey: "my value"}
   ,myObjJSON = JSON.stringify(myObj);

基于评论:
没有 JSON 对象 即可。有JSON字符串,可以解析到Javascript对象。 Javascript对象可以 stringified 到JSON字符串。在JSON字符串内引用了键和值。所以上面的结果是一个 string ,其中包含'{mykey:my value}'

Based on comments: There is no such thing as a JSON Object. There are JSON-strings, which can be parsed to Javascript Objects. Javascript Objects can be stringified to JSON strings. Within a JSON-string keys and values are quoted. So the result of the above is a string containing '{"mykey":"my value"}'.

尝试在浏览器控制台中解析 myObjJSON (使用: JSON.parse(myObjJSON) )你得到:对象{mykey:我的价值}

Try parsing myObjJSON in your browser console (using: JSON.parse(myObjJSON)) and you get: Object {mykey: "my value"}.

这篇关于带或不带引号的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆