我应该如何在JavaScript中将JSON字符串转换为对象?是否有相应的方法可以实现?
例如:
var x = "{ id: 5, name: 'hello' }";
var y = /*something*/(x);
alert(y.id + " " + y.name);
我应该如何在JavaScript中将JSON字符串转换为对象?是否有相应的方法可以实现?
例如:
var x = "{ id: 5, name: 'hello' }";
var y = /*something*/(x);
alert(y.id + " " + y.name);
parseJSON()
函数是很好的。如果您还没有升级到1.4.1,请考虑升级。以下是其API文档中相关部分的摘录:
Description: Takes a well-formed JSON string and returns the resulting JavaScript object.
jQuery.parseJSON( json ) version added: 1.4.1
json The JSON string to parse.
Passing in a malformed JSON string will result in an exception being thrown. For example, the following are all malformed JSON strings:
{test: 1}
(test does not have double quotes around it).{'test': 1}
('test' is using single quotes instead of double quotes).Additionally if you pass in nothing, an empty string, null, or undefined, 'null' will be returned from
parseJSON
. Where the browser provides a native implementation ofJSON.parse
, jQuery uses it to parse the string. For details on the JSON format, see http://json.org/.Example:
Parse a JSON string.
var obj = jQuery.parseJSON('{"name":"John"}'); alert( obj.name === "John" );
jquery
标签,但是以后请注意,标签是为了 问题 而设定的,而不是为了回答。即使提问者对 jQuery 感兴趣,问题也没有将选择范围缩小到 jQuery。在 6 个回答中,只有你的回答与 jQuery 相关。基本上,这不是一个 jQuery 的问题,不应该被标记为这样的标签。 - BlixtBruno,
这里是 jQuery 方法,你会看到它使用了完全相同的 new Function("return..)。
parseJSON: function (a) {
if (typeof a !== "string" || !a) return null;
if (/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
.replace(/(?:^|:|,)(?:\s*\[)+/g, "")))
return z.JSON && z.JSON.parse ? z.JSON.parse(a) : (new Function("return " + a))();
else c.error("Invalid JSON: " + a)
}
[编辑] 正则表达式当然是在处理嵌入在 JSON 字符串中的任何恶意字符。
虽然有点可怕 :)
这段文字完整地介绍了本地JSON实现和使用本地JSON实现的库: http://en.wikipedia.org/wiki/JSON#Native_JSON
使用本地JSON实现比使用某些JavaScript库执行相同任务要快得多/更安全。然而,如果某个库声称它会尽可能使用本地实现-那么它甚至比直接使用本地JSON更好(兼容性等方面)。
JSON.org网站提供了最简单的解决方案:
var y = eval('(' + x + ')');
编辑:哦。对了。如果你确定可以信任源代码生成正确的JSON对象,那么eval
解决方案是很好的。否则,你将不得不使用JSON解析器 - 查看其他回复。
你还可以尝试以下方法,比使用 eval() 函数略微安全:
var x = '{ "id": 5, "name": "hello" }';
var y = new Function("return " + x)();
alert(y.id + " " + y.name);
虽然其他人已经说过了,如果你正在使用 jQuery,可以选择内置的 parseJson 方法。
JSON.parse
方法:var myObject = JSON.parse(
'{ "id": 5, "name": "hello" }');
所有现代浏览器都内置了此功能,而在最初提出这个问题时,大多数浏览器已经内置了它。
JSON
对象,我有一个字符串
,所以是从字符串转换为JSON
。 - BrunoLM