Reputation: 17940
I need to pass different strings formatted as json to a json parser.
Problem is that jQuery.parseJSON() and JSON.parse() only support a very strict json format:
Passing in a malformed JSON string may result in an exception being thrown. For example, the following are all malformed JSON strings:
{test: 1} (test does not have double quotes around it).
{'test': 1} ('test' is using single quotes instead of double quotes).
Is there a less restrictive parser that will allow passing values like that (without quotes or with single quote)?
BTW, I'm using KO 2.2.1 so if it has something like that it would be helpful.
Upvotes: 2
Views: 1819
Reputation: 4002
JSON5 is the most common solution to this now.
JSON5 supports unquoted keys, single quotes, comments, trailing commas, etc.
Upvotes: 0
Reputation: 624
There is a node module called jsonic that parses non strict JSON.
npm install jsonic
You might also use eval:
var parsed = eval(json)
Be careful because eval
could also run code so you must be sure that you know what you are parsing.
Upvotes: 3
Reputation: 71939
There is no such thing as a less strict JSON parser. You're either dealing with well-formed JSON, or you're not dealing with JSON at all. To parse your custom format, you may want to take a look at Crockford's parser source code, and modify it to fit your needs.
Or, for a quick and dirty solution you might just use eval
(but be aware its use has security implications).
Upvotes: 1