Javascript JSON 字符串转 JS 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2257117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON string to JS object
提问by Vinod
I am using a JS object to create graphs with Google visualization. I am trying to design the data source. At first, I created a JS object client-side.
我正在使用 JS 对象通过 Google 可视化创建图形。我正在尝试设计数据源。首先,我在客户端创建了一个 JS 对象。
var JSONObject = {
cols: [{
id: 'date',
label: 'Date',
type: 'date'
},
{
id: 'soldpencils',
label: 'Sold Pencils',
type: 'number'
},
{
id: 'soldpens',
label: 'Sold Pens',
type: 'number'
}
],
rows: [{
c: [{
v: new Date(2008, 1, 1),
f: '2/1/2008'
}, {
v: 30000
}, {
v: 40645
}]
},
{
c: [{
v: new Date(2008, 1, 2),
f: '2/2/2008'
}, {
v: 14045
}, {
v: 20374
}]
},
{
c: [{
v: new Date(2008, 1, 3),
f: '2/3/2008'
}, {
v: 55022
}, {
v: 50766
}]
}
]
};
var data = new google.visualization.DataTable(JSONObject, 0.5);
Now I need to fetch the data dynamically. So I send an AJAX request to a page that returns the JSON string:
现在我需要动态获取数据。所以我向一个返回 JSON 字符串的页面发送了一个 AJAX 请求:
"cols: [{id: 'date', label: 'Date', type: 'date'},
{id: 'soldpencils', label: 'Sold Pencils', type: 'number'},
{id: 'soldpens', label: 'Sold Pens', type: 'number'}],
rows: [{c:[{v: new Date(2008,1,1),f:'2/1/2008'},{v: 30000}, {v: 40645}]},
{c:[{v: new Date(2008,1,2),f:'2/2/2008'},{v: 14045}, {v: 20374}]},
{c:[{v: new Date(2008,1,3),f:'2/3/2008'},{v: 55022}, {v: 50766}]}"
This I save into a variable:
这我保存到一个变量中:
var var1 = "cols: [{i ....... 66}]}"
and show as
并显示为
alert(var1);
Now my task is to create a JS object from this string. This is not working. When I use a JS object, everything works fine and I am able to get my required graph. Now if I try putting the same value of string from the AJAX request which I confirmed from a alert message into a n object, the object is not getting created correctly. Please let me know your opinion and any correction or advices.
现在我的任务是从这个字符串创建一个 JS 对象。这是行不通的。当我使用 JS 对象时,一切正常,我能够获得所需的图形。现在,如果我尝试将来自警报消息的 AJAX 请求中的相同字符串值放入对象中,则该对象未正确创建。请让我知道您的意见和任何更正或建议。
回答by Andy E
Some modern browsers have support for parsing JSON into a native object:
一些现代浏览器支持将 JSON 解析为原生对象:
var var1 = '{"cols": [{"i" ....... 66}]}';
var result = JSON.parse(var1);
For the browsers that don't support it, you can download json2.js from json.orgfor safe parsing of a JSON object. The script will check for native JSON support and if it doesn't exist, provide the JSON global object instead. If the faster, native object is available it will just exit the script leaving it intact. You must, however, provide valid JSON or it will throw an error — you can check the validity of your JSON with http://jslint.comor http://jsonlint.com.
对于不支持的浏览器,可以从json.org下载json2.js来安全解析 JSON 对象。该脚本将检查原生 JSON 支持,如果它不存在,则提供 JSON 全局对象。如果更快的本地对象可用,它将退出脚本而保持原样。但是,您必须提供有效的 JSON,否则会抛出错误 — 您可以使用http://jslint.com或http://jsonlint.com检查 JSON 的有效性。
回答by whackamole
You can use eval(jsonString) if you trust the data in the string, otherwise you'll need to parse it properly - check json.org for some code samples.
如果您信任字符串中的数据,您可以使用 eval(jsonString) ,否则您需要正确解析它 - 检查 json.org 以获取一些代码示例。
回答by filippo
the string in your question is not a valid json string. From json.org website:
您问题中的字符串不是有效的 json 字符串。从json.org 网站:
JSON is built on two structures:
* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. * An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
JSON 建立在两种结构上:
* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. * An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
Basically a json string will always start with either { or [.
基本上一个 json 字符串总是以 { 或 [ 开头。
Then as @Andy E and @Cryo said you can parse the string with json2.js or some other libraries.
然后正如@Andy E 和@Cryo 所说,您可以使用 json2.js 或其他一些库来解析字符串。
IMHO you should avoid eval because it will any javascript program, so you might incur in security issues.
恕我直言,您应该避免使用 eval,因为它会运行任何 javascript 程序,因此您可能会遇到安全问题。
回答by nortron
You can use this libraryfrom JSON.org to translate your string into a JSON object.
您可以使用JSON.org 中的这个库将您的字符串转换为 JSON 对象。
var var1_obj = JSON.parse(var1);
Or you can use the jquery-jsonlibrary as well.
或者您也可以使用jquery-json库。
var var1_obj = $.toJSON(var1);
回答by Gumbo
The string you are returning is not valid JSON. The names in the objects needs to be quoted and the whole string needs to be put in { … }to form an object. JSON also cannot contain something like new Date(). JSON is just a small subset of JavaScript that has only strings, numbers, objects, arrays, true, falseand null.
您返回的字符串不是有效的 JSON。对象中的名称需要被引用,并且需要将整个字符串放入{ … }以形成一个对象。JSON 也不能包含类似new Date(). JSON 只是 JavaScript 的一个小子集,它只有字符串、数字、对象、数组true、false和null。
See the JSON grammarfor more information.
有关更多信息,请参阅JSON 语法。

