首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从字符串中提取JSON对象并将其添加到数组中?

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

Stack Overflow用户
提问于 2015-04-16 20:17:36
回答 2查看 6.4K关注 0票数 -1

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

示例字符串:

代码语言:javascript
复制
"I was with {"name":"John"}{"name":"Anne"}{"name":"Daniel"} yesterday"`

如何从这个示例字符串中提取JSON对象?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-04-16 20:48:53

一种方法是使用str.search(regexp)函数查找满足JSON regex found here的所有部分。因此,您可以编写一个在字符串中搜索regexp匹配的函数。

要从字符串中实际提取对象,可以使用these two functions for the regex,然后遍历字符串,直到找到所有对象。

代码语言:javascript
复制
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));
}
票数 0
EN

Stack Overflow用户

发布于 2015-04-16 20:21:27

代码语言:javascript
复制
var a = JSON.parse('{"name":"John"}');

==>对象{name:"John"}

代码语言:javascript
复制
var b = [];
b.push(a);
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29674495

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档