views:

65

answers:

2
{"0":{"name":{"name_id":"How to battle","tab_level":"2"},"job_reward":{"job_money":"10000","job_exp":"50","job_energy":"23"}},"job_required_items":[{"filename":"sword.gif","no":"2"}],"1":{"name":{"name_id":"Check for battle","tab_level":"2"},"job_reward":{"job_money":"1000","job_exp":"12","job_energy":"10"}}}

i want to parse this json format using for.

+3  A: 
JSON.parse(json_string);

in older browsers you'll need this

helle
A: 

In modern browsers you can do:

JSON.parse(json);

If you want it to work for older ones you may consider using the offical parser from json.org.

If the response is from you, you can parse it natively by:

var o = new Function( "return " + json )();

which is even faster than the usual:

var o = eval( "(" + json + ")" );
galambalazs
you should check if the JSON is valid before doing this.
Luca Matteis
Both of these methods are actually quite dangerous since they open possibilities for arbitrary code execution. Better use a JSON parser library that does NOT rely on eval() or the Function() constructor.
Techpriester
I said: "If the response is from you". **There are cases** when it's simpler to use native parsing, and you don't have any security threat.
galambalazs
Sorry, but thinking that security issues cannot happen to you because all code comes from you is exactly what leads to a lot of vulnerabilities. You can never be absolutely sure if any foreign code can enter your system and because of that, it's dangerous to open the possibility of execution, even if "everything comes from yourself". And in what way is eval('('+json+')') simpler than JSON.parse(json) ?
Techpriester
it's faster because no library is needed to be dowloaded, and the browser parses it by it's own JS engine. I repeat myself: **there are cases**, in which you can use eval. Even Crockford said that before native JSON parsers came along...
galambalazs