简体   繁体   中英

Error when converting eval() to JSON.parse()

I have a snippet code with eval() as shown below:

 var data = "{listUpdated:[],listConflictOrMerge:[]}"; //returned from Ajax var results = eval("(" + data + ")"); console.log(results) 

As you can see, the data is my input value returned from ajax request. When using eval(), it can be parsed to 2 array objects.

And now I don't want to use eval() anymore, so I try using JSON.parse(). However, there is an error.

 var data = "{listUpdated:[],listConflictOrMerge:[]}"; //returned from Ajax var results = JSON.parse(data); console.log(results) 

my purpose is that I don't want to use eval() to parse data anymore.

  • So, is there any ways can do that?.

  • I try using JSON, but I got unlucky. Am I wrong somewhere?

The data you're trying to parse isn't valid JSON, so JSON.parse can't parse it.

Keys in JSON objects must be quoted, just like any other string. The form you're using is valid in Javascript, but invalid in JSON.

 var data = '{"listUpdated":[],"listConflictOrMerge":[]}'; var results =JSON.parse(data); console.log(results) 

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