JSON parsing

A badly formed JSON string from a third party is sent to me. I tried using JSON.parse(str) to parse it in a JavaScript object, but of course it failed.

The reason is that keys are not strings:

 {min: 100} 

Unlike a valid JSON string (which is perfectly parsed):

 {"min": 100} 

I need to accept a string created due to an irregular shape. I think that forgetting to quote keys correctly is a common mistake. Is there a good way to change this to a valid JSON string so that I can parse it? At this point, I may have to disassemble the character by character and try to form an object that sounds awful.

Ideas?

+8
javascript
source share
3 answers

You can simply evaluate, but it will be a bad security practice if you do not trust the source. The best solution would be to either change the line manually to quote the keys, or use a tool written by someone else to do it for you (check out https://github.com/daepark/JSOL written by daepark).

+5
source share

I did this most recently, using Uglifyjs to evaluate:

 var jsp = require("uglify-js").parser; var pro = require("uglify-js").uglify; var orig_code = "var myobject = " + badJSONobject; var ast = jsp.parse(orig_code); // parse code and get the initial AST var final_code = pro.gen_code(ast); // regenerate code $('head').append('<script>' + final_code + '; console.log(JSON.stringify(myobject));</script>'); 

This is really messy and has all the same problems as the eval () -based solution, but if you just need to parse / reformat the data once, then the above should provide you with a clean copy of the JSON JS object.

+2
source share

Depending on what else is in JSON, you can simply replace the string and replace '{' with '{"' and ':' with '":' .

+1
source share

All Articles