Parsing JSON Response Problem
Solution 1:
eval is not recommended (security wise), use the JSON parser:
var obj = JSON.parse(result);
or to be sure that it works even if the browser does not have a JSON parser:
var obj = typeof JSON !='undefined' ? JSON.parse(result) : eval('('+result+')');
This is however not recommended and you should in that case prefer to include an alternate JSON library as recommended in this answer comments (see json.org).
Then you can do:
var id = obj.item.cid;
var name = obj.item.name;
Solution 2:
Eval the entire assignment instead.
var obj;
eval('obj = ('+s+')');
console.log(obj.item.name);
Or use json2 instead.
Solution 3:
Use the standard way to parse JSON and use a proper library to fill the gaps in old browsers, like https://github.com/douglascrockford/JSON-js
Download json.js, and add a reference to it to your page by using a <script>
tag. The script will automatically supply the required JSON methods if your browser doesn't already.
var object = JSON.parse(yourJSONString);
Eval is not recommended, and you could even call it forbidden, to use it to parse JSON. For the simple reason that any Javascript inside the string would be evaluated, and would allow for code injection. eval
in any language is dangerous and certainly not to be used if there is any chance the input is insecure.
Post a Comment for "Parsing JSON Response Problem"