最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to convert a JSON string to an object? - Stack Overflow

programmeradmin0浏览0评论

How can I convert a JSON string to an object in JavaScript? Is there a method that does this?

Something like:

var x = "{  id: 5, name: 'hello'  }";
var y = /*something*/(x);

alert(y.id + " " + y.name);

How can I convert a JSON string to an object in JavaScript? Is there a method that does this?

Something like:

var x = "{  id: 5, name: 'hello'  }";
var y = /*something*/(x);

alert(y.id + " " + y.name);
Share Improve this question edited Jun 11, 2010 at 12:09 BalusC 1.1m376 gold badges3.6k silver badges3.6k bronze badges asked Jun 10, 2010 at 11:17 BrunoLMBrunoLM 100k86 gold badges308 silver badges460 bronze badges 7
  • Without or without frameworks (jQuery etc.)? – kennytm Commented Jun 10, 2010 at 11:18
  • (And please, no eval.) – kennytm Commented Jun 10, 2010 at 11:19
  • am i missing something? looks like convert from JSON, not to – Andrey Commented Jun 10, 2010 at 11:25
  • 2 @Bruno: It is a string encoded in JSON. You want to convert a JSON-encoded string into Javascript objects. (JSON = Javascript Object Notation.) – kennytm Commented Jun 10, 2010 at 11:29
  • 4 @Bruno: Also, your string is not in valid JSON syntax. – kennytm Commented Jun 10, 2010 at 11:35
 |  Show 2 more comments

7 Answers 7

Reset to default 9

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:

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 of JSON.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" );

Use json2 lib : http://www.json.org/js.html

Bruno,

here's the jquery method, which as you'll see, uses the self same new Function("return..) business.

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)
}

[edit] the regex is of course 'dealing' with any rogue characters embedded within ther json string.

spooky tho :)

This paragraph fully covers the native JSON implementations, and libraries that use native JSON implementations: http://en.wikipedia.org/wiki/JSON#Native_JSON

Using native JSON implementation will be considerably faster/safer than using some javascript libraries for same task. However, if some library claims it will try using native implementation whenever possible - it's even better choice that using native JSON directly (compatibility and stuff).

The JSON.org website gives the simplest solution:

var y = eval('(' + x + ')');

More information

Edit: Oh. Right. The eval solution is good if and only if you are sure that you can trust the source to produce correct JSON objects. Otherwise, you will have to use a JSON parser - look at the other replies.

you can also do the following which is slighly less evil than eval :) :

var x = '{  "id": 5, "name": "hello"  }';

var y = new Function("return " + x)();
alert(y.id + " " + y.name);

tho as said by others, if you're using jquery, go for the inbuilt parseJson method.

The modern answer to this question is to use JSON.parse:

var myObject = JSON.parse(
    '{  "id": 5, "name": "hello"  }');

All modern browsers have this function built in, and most of them had it built in when the question was first asked.

发布评论

评论列表(0)

  1. 暂无评论