从包含JSON对象

时间:2016-09-13 23:11:17

标签: javascript json

我有一个像

这样的字符串
"Something has happened {\"prop1\":{\"name\":\"foo\"}}"

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

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

在JavaScript中,实现这一目标的好方法是什么。

字符串中可以有多个对象,并且不知道对象可能包含许多嵌套对象或数组。提前谢谢。

2 个答案:

答案 0 :(得分:1)

  

最小值只是打印字符串

那好吧。一个非常简单,非优化,不一定强大的漂亮打印功能可能看起来像这样:

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));

上面的内容不允许在属性中使用转义引号,也可能是一些我没想到的用于快速演示的其他内容,但我将这些内容作为练习留给读者... < / p>

P.S。 string .repeat() method可能需要填充。

答案 1 :(得分:0)

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

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