4

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...
Community
  • 1
  • 1
Lance
  • 75,200
  • 93
  • 289
  • 503

2 Answers2

5

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

Jon
  • 428,835
  • 81
  • 738
  • 806
  • It is not working for me for some reason, it's saying `SyntaxError: Unexpected token`... – Lance Aug 02 '12 at 22:15
  • 1
    @LancePollard: There's a comma missing after the `10`. – Jon Aug 02 '12 at 22:17
  • Sorry, that wasn't the issue, here is the problem: http://jsfiddle.net/eLxgB/1/ – Lance Aug 02 '12 at 22:22
  • 1
    @LancePollard: Those ` ` entities are *not* valid JSON though (the browser renders them as whitespace when part of HTML, but they mess up JSON). [If you remove them it's all good](http://jsfiddle.net/G6HbG/). – Jon Aug 02 '12 at 22:24
1

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

valentinas
  • 4,277
  • 1
  • 20
  • 27