Javascript 如何从字符串中提取JSON对象并将其添加到数组中?

Javascript 如何从字符串中提取JSON对象并将其添加到数组中?,javascript,json,Javascript,Json,我想从随机包含JSON对象的字符串中提取所有JSON对象,并将它们添加到数组中 示例字符串: "I was with {"name":"John"}{"name":"Anne"}{"name":"Daniel"} yesterday"` 如何从这个示例字符串中提取JSON对象 var a = JSON.parse('{"name":"John"}'); a==>对象{name:“John”} 一种方法是使用str.search(regexp)函数来查找实现JSON正则表达式的所有部分。因此,

我想从随机包含JSON对象的字符串中提取所有JSON对象,并将它们添加到数组中

示例字符串:

"I was with {"name":"John"}{"name":"Anne"}{"name":"Daniel"} yesterday"`
如何从这个示例字符串中提取JSON对象

var a = JSON.parse('{"name":"John"}');
a==>对象{name:“John”}


一种方法是使用str.search(regexp)函数来查找实现JSON正则表达式的所有部分。因此,您可以编写一个函数,在字符串上搜索regexp匹配项

要从字符串中实际提取对象,可以使用,然后在字符串上循环,直到找到所有对象

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

发布您的示例JSON stringShow代码,展示您迄今为止尝试的内容。。。您可以使用JSON.parse(jsonString);其中jsonString是有效的jsonString,是否要为其中的任何JSON对象解析具有半随机内容的字符串?是的!然后将这些对象添加到数组中。很抱歉,我的意思是,除了“John”之外,还会有其他内容和其他名称。@FadiY你能在你的问题中添加一个要分析的示例字符串吗?@FadiY我不明白你在找什么?对于您给出的示例字符串,上面的代码将起作用。“==>”似乎对我不起作用。您确定它不应该是“==”?@FadiY,这是变量a的输出的示例。这不是javascript代码。看起来应该可以。我会尝试一下,稍后再告诉你它是如何运行的。我正在处理细节,但这目前只返回json对象的起始索引,你需要的是计算出对象被提取的时间。一个解决方案可能是在这里合并正则表达式搜索的第一个索引和最后一个索引:这也很有用。实际上,您可以使用splice进行提取和删除。
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));
}