Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse ill formed JSON string

I am being sent an ill formed JSON string from a third party. I tried using JSON.parse(str) to parse it into a JavaScript object but it of course failed.

The reason being is that the keys are not strings:

{min: 100}

As opposed to valid JSON string (which parses just fine):

{"min": 100}

I need to accept the ill formed string for now. I imagine forgetting to properly quote keys is a common mistake. Is there a good way to change this to a valid JSON string so that I can parse it? For now I may have to parse character by character and try and form an object, which sounds awful.

Ideas?

like image 576
lostintranslation Avatar asked Apr 19 '13 17:04

lostintranslation


People also ask

What error does JSON parse () throw when the string to parse is not valid JSON?

JSON. parse() takes a JSON string and transforms it into a JavaScript object. Trailing commas are not valid in JSON, so JSON. parse() throws an error if the string passed to it has trailing commas.

How do I check if a string is JSON Parsable?

In order to check the validity of a string whether it is a JSON string or not, We're using the JSON. parse()method with few variations. This method parses a JSON string, constructs the JavaScript value or object specified by the string.

How do I check if a JSON string is valid?

The common approach for checking if a String is a valid JSON is exception handling. Consequently, we delegate JSON parsing and handle the specific type of error in case of incorrect value or assume that value is correct if no exception occurred.

Is empty string a valid JSON?

Empty ValuesNull values and empty strings (“”) are valid JSON values, but the state of being undefined is not valid within JSON.


2 Answers

You could just eval, but that would be bad security practice if you don't trust the source. Better solution would be to either modify the string manually to quote the keys or use a tool someone else has written that does this for you (check out https://github.com/daepark/JSOL written by daepark).

like image 75
huwiler Avatar answered Oct 16 '22 18:10

huwiler


I did this just 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 sloppy in a way, and has all the same problems as an eval() based solution, but if you just need to parse/reformat the data one time, then the above should get you a clean JSON copy of the JS object.

like image 28
BishopZ Avatar answered Oct 16 '22 19:10

BishopZ