从包含JSON对象的字符串解析JSON
Parsing JSON from string containing JSON object
我有一个字符串像
"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);
相关文章:
- 如何使用JSON字符串中的jQuery填充下拉框
- Json字符串可以'当字符串末尾有“'时,t解码;
- jquery从2个json字符串构建一个复选框表单
- RegEx只匹配JSON字符串中最里面的数组
- json字符串的Javascript帖子:没有任何东西传入或返回
- 使用javascript在MVC视图中解析.net JSON字符串
- 用Angularjs+Typescript将GZip Json字符串解压为普通Json字符串
- 如何将表单数据传递给PHP并将json字符串返回给Javascript
- 如何使用AngularJS应用基于Json字符串响应的条件CSS类
- 停止JSON.parse()从JSON字符串数据中删除尾随零
- 将JSON字符串转换为函数参数
- 在AngularJS中创建JSON字符串
- 为什么我不能使用jQuery.parseJSON(json)解析json字符串
- Json字符串更改日期
- JSON字符串格式错误
- Json和$scope的角度之间的差异$eval应用于JSON字符串时
- C#JSON字符串到JavaScript数组
- 如何在JSON字符串中实现嵌套HTML
- 如何从带有多个对象的JSON字符串创建JSON对象
- 使用捕获组查找和替换json字符串中出现的所有短语