-5

I have a json string like this

{
 [
  {"plan": "basic", "plan_id": "sub33"},
  {"plan": "advanced", "plan_id: "sub44"}
 ]
}

How can I create a JSON object from the above?

When I try to parse it I get an error:

var obj = jQuery.parseJSON( '{[{"plan": "basic", "plan_id": "sub33"},{"plan": "advanced", "plan_id: "sub44"}]}' );
(program):1 Uncaught SyntaxError: Unexpected token [
var obj = jQuery.parse( '{[{"plan": "basic", "plan_id": "sub33"},{"plan": "advanced", "plan_id: "sub44"}]}' );
VM8143:2 Uncaught TypeError: undefined is not a function
Anthony
  • 33,838
  • 42
  • 169
  • 278

3 Answers3

6

First, you need valid JSON. Your example isn't valid, it needs a key for the array, e.g.:

{
 "array": [
  {"plan": "basic", "plan_id": "sub33"},
  {"plan": "advanced", "plan_id": "sub44"}
 ]
}

Or, if you just want an array and not an object wrapper around it:

[
  {"plan": "basic", "plan_id": "sub33"},
  {"plan": "advanced", "plan_id": "sub44"}
]

How can I create a JSON object from the above?

You don't, you already have a "JSON object" (text that defines an object). JSON is a textual notation for data exchange; when you turn it into objects in memory, it's not text anymore, so it's not JSON anymore. (Just like a DOM element isn't an HTML string, even though it may have been created from an HTML string.)

To turn it into a JavaScript object, you use JSON.parse (jQuery.parseJSON is fine too, and useful for really old browsers, but all modern browsers have JSON.parse now):

var obj = JSON.parse(yourString);

Example:

var yourString = '{' +
    '"array": ' +
    ' [' +
    '  {"plan": "basic", "plan_id": "sub33"},' +
    '  {"plan": "advanced", "plan_id": "sub44"}' +
    ' ]' +
    '}';
var obj = JSON.parse(yourString);
snippet.log(obj.array[0].plan); // "basic"
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Or if you just want the array:

Example:

var yourString =
    '[' +
    '  {"plan": "basic", "plan_id": "sub33"},' +
    '  {"plan": "advanced", "plan_id": "sub44"}' +
    ']';
var array = JSON.parse(yourString);
snippet.log(array[0].plan); // "basic"
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Simply be removing excessive {}. And correcting typo "plan_id**"**:

var x = [
  {"plan": "basic", "plan_id": "sub33"},
  {"plan": "advanced", "plan_id": "sub44"}
];

//x is JS object. JSON is notation, not a constructor. You can stringify to send over the wire, like JSON.stringify(x), this will give you a JSON-string: "[{"plan":"basic","plan_id":"sub33"},{"plan":"advanced","plan_id":"sub44"}]"

blade091
  • 642
  • 4
  • 10
-2

You can use JSON.parse(jsonString)

meteor
  • 2,518
  • 4
  • 38
  • 52