Reputation: 2871
I am trying to parse a string which in JSON format only that keys are not enclosed in quotes. I can very well parse this string in Javascript, but can not find a Java API which will help me parse this. All the APIs I tried assumes strict JSON format.
Can anyone suggest a library which has an option to parse this, or a whole new approach to the problem (say like use regex instead) ?
Upvotes: 6
Views: 4383
Reputation: 624
You might 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.
There is also a node module called jsonic that parses non stirct JSON.
Upvotes: 0
Reputation: 5410
Here's a solution in coffeescript using the underscore library. If you're not using that you can replace _.foldl with a for loop.
parseNonStrictJson = (value) ->
inQuote = false
correctQuotes = (memo, nextChar) ->
insertQuote =
(inQuote and not /[a-z0-9_"]/.test nextChar) or
(!inQuote and /[a-z_]/.test nextChar)
inQuote = (inQuote != (insertQuote or nextChar == '"') )
memo + (if insertQuote then '"' else '') + nextChar
valueWithQuotes = _.foldl(value + '\n', correctQuotes, "")
JSON.parse(valueWithQuotes)
And the same in javascript:
function parseNonStrictJson(value) {
var correctQuotes, inQuote, valueWithQuotes;
inQuote = false;
correctQuotes = function(memo, nextChar) {
var insertQuote;
insertQuote = (inQuote && !/[a-z0-9_"]/.test(nextChar)) || (!inQuote && /[a-z_]/.test(nextChar));
inQuote = inQuote !== (insertQuote || nextChar === '"');
return memo + (insertQuote ? '"' : '') + nextChar;
};
valueWithQuotes = _.foldl(value + '\n', correctQuotes, "");
return JSON.parse(valueWithQuotes);
};
Upvotes: 2
Reputation: 21182
Personally, you could use a state pattern and add your quotes. Unless I am wrong, the state pattern would read in character by character and set flags to indicate whether we are within a double quote condition and whether our double quotes are "quoted" with a backslash. Using this, and that variable names don't start with a number, you could add the quotes while streaming it, then send it on it's way.
Upvotes: 0
Reputation: 29267
If the keys aren't enclosed in quotes then it's not JSON.
You should either hack this yourself or find someone who did it already.
Also, there's no such thing as non-strict json. There's only 1 version of JSON and it's strict.
Upvotes: 1