parsing JSON using javascript gives me undefined while getting the value from the json response
i am parsing an json string usin javascript
{
"head": {
"example": "0"
},
"res": {
"@test": "121",
"@found": "5"
}
}
i am getting the http response from the remote site and i am using javascript to extract the @found value .i used the below code .
var json=eval('('+request.responseText+')');
alert(json.head.res.@found);
gives me a null value c开发者_如何学Goan u please tell me how can i parse this.
alert(json.head.res['@found']);
@ is not valid to start a variable name, so you have to use bracket notation. Or change the variable name to be valid.
Basically, in regular expression form: [a-zA-Z_$][0-9a-zA-Z_$]*. In other words, the first character can be a letter or _ or $, and the other characters can be letters or _ or $ or numbers.
What characters are valid for JavaScript variable names?
Per Topera's answer head and res are on the same level in your object not nested.
Attribute "res" is not inside "head" attribute.
Try this: json.res['@found']
Try json.res['@found']
. JavaScript object properties that are not valid variable names cannot be accessed using dot notation. Also, as noted by others, @found is not in head.
fix these 3 things :
@
is not a valid variable name character. you should consider the[]
syntax instead of the "dot" one.res
is not inhead
.- please don't use
eval
. I strongly advise you to useJSON.parse
instead ofeval
var json = JSON.parse(request.responseText); alert(json.res['@found']);
alert(json.res['@found']);
res
is not inside head.
精彩评论