我正在尝试解析一个字符串,该字符串采用 JSON 格式,只是键未包含在引号中。我可以很好地用 Javascript 解析这个字符串,但是找不到可以帮助我解析它的 Java API。我尝试过的所有 API 都采用严格的 JSON 格式。
谁能推荐一个可以解析这个选项的库,或者一个全新的解决问题的方法(比如改用正则表达式)?
最佳答案
这是使用下划线库的 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);
};
关于java - 使用 Java 解析非严格的 json,其中键不包含在引号中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2993848/