简体   繁体   中英

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 receive 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 :(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM