javascriptjqueryjsonknockout.js

Need less restrictive json parser


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.


Solution

  • 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).