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>