我想从一个随机包含它们的字符串中提取所有JSON对象,并将它们添加到一个数组中。
示例字符串:
"I was with {"name":"John"}{"name":"Anne"}{"name":"Daniel"} yesterday"`
如何从这个示例字符串中提取JSON对象?
发布于 2015-04-16 20:48:53
一种方法是使用str.search(regexp)函数查找满足JSON regex found here的所有部分。因此,您可以编写一个在字符串中搜索regexp匹配的函数。
要从字符串中实际提取对象,可以使用these two functions for the regex,然后遍历字符串,直到找到所有对象。
var match = str.match(regex);
var firstIndex = str.indexOf(match[0]);
var lastIndex = str.lastIndexOf(match[match.length-1]);
var JSONobjects = [];
while( str.match(regex){
//extract the wanted part.
jsonObject = substr(str.indexOf(match[0],str.lastIndexOf(match[match.length1-]));
//remove the already found json part from the string and continue
str.splice(str.indexOf(match[0],str.indexOf(match[0] + jsonObject.length());
//parse the JSON object and add it to an array.
JSONobjects.push(JSON.parse(jsonObject));
}
发布于 2015-04-16 20:21:27
var a = JSON.parse('{"name":"John"}');
==>对象{name:"John"}
var b = [];
b.push(a);
https://stackoverflow.com/questions/29674495
复制相似问题