Parsing lax json in which keys are not enclosed in quotes, with Java

I am trying to parse a string that is in JSON format only in that the keys are not enclosed in quotation marks. I parse this line very well in Javascript, but can't find a Java API to help me parse this. All the APIs I tried assume a strict JSON format.

Can anyone suggest a library that has the ability to parse this or a completely new approach to the problem (say, how to use a regular expression)?

+3
source share
4 answers

If the keys are not quoted, then this is not JSON.

You must either hack it yourself, or find someone who has already done it.

, , json. 1 JSON .

+1

coffeescript . , _.foldl for.

 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)

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);
};
+1

. , , , . , , , .

0

eval:

var parsed = eval(json)

Be careful because it evalcan 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 unexcited JSON.

0
source

Source: https://habr.com/ru/post/1748941/


All Articles