How to parse pretty JSON in JavaScript

Possible Duplicate:
How to parse JSON in JavaScript

If you have JSON formatted like this:

{
  "id": 10,
  "user": {
    "email": "example.com"
  }
}

What is the standard way of parsing that into a JSON object in JavaScript? The use case is if a user is entering JSON into a textarea, parsing that out.

I started doing this but don't want to go down this road if there's already a robust/standard solution:

JSON.parse($('#the-textarea').val().replace(/^s+/mg, '').replace(/n/g, '')); // not quite right yet, still not parsable...

You don't need to do anything. This non-significant whitespace does not make for invalid JSON and will be ignored by the parser.


This should do the trick:

var result = jQuery.parseJSON(jQuery('#the-textarea').val());

By the way, your example is not valid JSON, it's missing a comma. Here is a valid JSON example:

{
  "id": 10,
  "user": {
    "email": "example.com"
  }
}

http://jsonlint.com/ is your friend ;)

链接地址: http://www.djcxy.com/p/8498.html

上一篇: 解析JSON文件并在HTML中使用它

下一篇: 如何在JavaScript中解析漂亮的JSON