json: how to get the json-string into a javascript object
i am converting my ajax code from xml to json, but i am missing something basic here:
when i receiv开发者_Python百科e the json-string on the client-side, what is the recommended way to convert it into a javascript object.
for example i get this string:
{"connectionid":12345}
and i would like to do something like this:
alert(xmlhttp.responseText.connectionid);
thanks!
Use JSON.parse()
, or eval()
, if you like to live dangerously (or fully trust where your JSON comes from).
If you happen to be using jQuery, you get $.parseJSON()
.
Most browsers (the recent ones at least.. not IE7) have a native JSON object that you can use to parse and stringify JSON.
alert(JSON.parse(xmlhttp.responseText).connectionid);
In browsers that don't support the JSON object, you can either use a JSON parser from JSON.org or use eval(), however eval() is quite dangerous and i definitly don't advise you to use it.
Call eval on the response text.
var response = eval(xmlHttp.responseText);
alert(response.connectionId);
you could use eval
check this out : http://www.json.org/js.html
edit - oops, others typed faster :(
精彩评论