从包含JSON对象的字符串解析JSON

Parsing JSON from string containing JSON object

本文关键字:JSON 字符串 对象 包含      更新时间:2023-09-26

我有一个字符串像

"Something has happened {'"prop1'":{'"name'":'"foo'"}}"

,我想解析出JSON,以便我可以格式化字符串。如:

Something has happened 
{
   "prop1":{
    "name":"foo"
     }
}

在JavaScript中,完成这个的好方法是什么?

字符串中可以有多个对象,对象也不会被知道,它可以包含许多嵌套的对象或数组。

最小值就是打印字符串

好了。一个非常简单的,非优化的,不一定健壮的漂亮打印函数可能看起来像这样:

function basicPrettyPrint(str) {
  var output = '';
  var indentLevel = 0;
  var indent = '  ';
  var inQuotes = false;
  for (var i = 0; i < str.length; i++) {
    var current = str[i];
    if (current === '"' && indentLevel > 0) {
      inQuotes = !inQuotes;
      output += current;
    } else if (inQuotes) {
      output += current;
    } else if (current === ',' && indentLevel > 0) {
      output += ','n' + indent.repeat(indentLevel);
    } else if (current === '{' || current === '[') {
      if (indentLevel === 0) output += ''n';
      output += current + ''n' + indent.repeat(++indentLevel);
    } else if (current === '}' || current === ']') {
      output += ''n' + indent.repeat(--indentLevel) + current;
      if (indentLevel === 0) output += ''n';
    } else {
      output += current;
    }
    if (indentLevel < 0) {
      // parse failure: unbalanced brackets. Do something.
    }
  }
  return output;
}
var input = 'Here is a "simple" object, for testing: {"prop1":{"name":"foo"}}And here is a more complicated one that has curly brackets within one of the property values:{"prop1":"{this is data, not an object}","arr":[1,{"a":"1","b":{"x":1,"y":[3,2,1]}},3,4]}And a non-nested array:[1,2,3]';
console.log(basicPrettyPrint(input));

上面不允许在属性中使用转义引号,可能还有一些其他的事情我没有考虑到,但我把这些事情留给读者作为练习…

注:字符串.repeat()方法可能需要填充。

我们可以假设'{'和'}'表示json的开始和结束。如果是,你可以得到一个子字符串;参见下面的代码。你也可以用正则表达式做同样的事情。

    var str = "Something has happened {'"prop1'":{'"name'":'"foo'"}}"
    var start = str.indexOf("{");
    var end = str.lastIndexOf("}");
    var json = str.substr(start, end);