如何将JSON字符串转换为对象? [英] How to convert a JSON string to an object?
问题描述
如何在JavaScript中将JSON字符串转换为对象?有没有这样做的方法?
How can I convert a JSON string to an object in JavaScript? Is there a method that does this?
类似于:
var x = "{ id: 5, name: 'hello' }";
var y = /*something*/(x);
alert(y.id + " " + y.name);
推荐答案
根据评论和问题历史,它看起来像是你已经在使用jQuery了。在这种情况下,最好知道jQuery附带一个新的 parseJSON() 版本1.4.1
功能 a>今年1月下旬发布。如果您尚未达到1.4.1,请考虑升级。以下是其API文档的相关摘录:
As per the comments and question history it look like that you're already using jQuery. In that case, it's good to know that jQuery ships with a new parseJSON()
function since version 1.4.1 which was released late January this year. Consider upgrading if you're not at 1.4.1 yet. Here's an extract of relevance from its API documentation:
描述:采用格式良好的JSON string并返回生成的JavaScript对象。
Description: Takes a well-formed JSON string and returns the resulting JavaScript object.
jQuery.parseJSON(json)版本添加: 1.4.1
json 要解析的JSON字符串。
json The JSON string to parse.
传入格式错误的JSON字符串将导致抛出异常。例如,以下是所有格式错误的JSON字符串:
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':1}
('test'正在使用单引号而不是双引号。。
{test: 1}
(test does not have double quotes around it).{'test': 1}
('test' is using single quotes instead of double quotes).
此外,如果您没有传入任何内容,空字符串,null或未定义,'null'将从 parseJSON
返回。在浏览器提供 JSON.parse
的本机实现的地方,jQuery使用它来解析字符串。有关JSON格式的详细信息,请参阅 http://json.org/ 。
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 of JSON.parse
, jQuery uses it to parse the string. For details on the JSON format, see http://json.org/.
示例:
解析JSON字符串。
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
这篇关于如何将JSON字符串转换为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!