What you’ve quoted is not valid JSON, and even with a minimal modification, it wouldn’t be an array. I suspect you just mean “object” (e.g., what PHP calls an associative array; really it’s a map). What you’ve quoted looks like part of a JSON object definition, but it’s missing the initial {
.
jQuery offers jQuery.parseJSON
for this very purpose:
var x = jQuery.parseJSON(strContainingJSON);
So adding the leading {
, here it is:
str="{" +
' "Level": {' +
' "@attributes": {' +
' "value": "",' +
' "type": "RelyingParty",' +
' "others": "false",' +
' "id": "1"' +
' }' +
' },' +
' "Role": {' +
' "@attributes": {' +
' "uuid": "838f7ee2-f11c-48f9-887f-8e485b74169b",' +
' "type": "ADMIN"' +
' }' +
' },' +
' "Timeline": "2012",' +
' "Timezone": "GMT+330"' +
'}';
var x = jQuery.parseJSON(str);
console.log(x.Timeline); // "2012"
Of course, you probably get str
from somewhere else (loading it from ajax or something), rather than directly in a string as in the above, but the end result is the same. Also note that if you are using ajax to load the JSON, if it’s served with the correct MIME type, jQuery will parse it automatically, and then hand your ajax success
function the resulting object.
If you really want an array (an ordered list), put [
at the beginning and ]
at the end, creating a one-entry array containing the object:
str="[" +
' {' +
' "Level": {' +
' "@attributes": {' +
' "value": "",' +
' "type": "RelyingParty",' +
' "others": "false",' +
' "id": "1"' +
' }' +
' },' +
' "Role": {' +
' "@attributes": {' +
' "uuid": "838f7ee2-f11c-48f9-887f-8e485b74169b",' +
' "type": "ADMIN"' +
' }' +
' },' +
' "Timeline": "2012",' +
' "Timezone": "GMT+330"' +
' }' +
']';
var x = jQuery.parseJSON(str);
console.log(x[0].Timeline); // "2012"
8
solved How to parse the Json using jquery [duplicate]