有所发现,例如获得JSON的数组中给定文本
问题描述:
我有一个文本字符串与多个JSON:有所发现,例如获得JSON的数组中给定文本
一些文字{“称号”:“谷歌”,“说明”:“搜索网页,图像, 视频等等。“ }然后再次显示一些文字{“title”:“Google”, “description”:“搜索网页,图片,视频等。” }一些文字 再次
这是JSON我可以有多个时间字符串:
{
"title":"xyz",
"description":"xyz",
"image":"https:\/\/www.google.com\/images\/logo.png",
"url":"https:\/\/www.google.com\/"
}
有没有什么办法让阵列中的所有JSON字符串。 感谢提前:)
答
如果您知道对象不包含嵌套对象,这个(很幼稚)方法可能会奏效:
var text = `some text { "title":"Google", "description":"Search webpages, images, videos and more." } then again some text { "title":"Google", "description":"Search webpages, images, videos and more." } some text again`;
const results = [].concat.apply(
[],
text.split('{').map(part => part.split('}'))
)
.filter((_, i) => i % 2)
.map(part => `{${part}}`)
.map(json => {
try {
return JSON.parse(json);
} catch (e) {
return null;
}
})
.filter(Boolean);
console.log(results);
答
您可以使用Object.values()
让所有的值。或者您使用map
来获取值。下面是例子两个:
var obj = {
"title": "xyz",
"description": "xyz",
"image": "https:\/\/www.google.com\/images\/logo.png",
"url": "https:\/\/www.google.com\/"
};
var arr = Object.values(obj);
console.log(arr);
var arr = Object.keys(obj).map(function(k) {
return obj[k]
});
console.log(arr);
答
使用RegExp获得所有匹配字符串JSON:
var re = new RegExp(/\{\s*"title"\s*:\s*(.+?)\s*,\s*"description":\s*(.+?)\s*,\s*"image":\s*(.+?)\s*,\s*"url":\s*(.+?)\s*}/, 'g');
var text = 'some text { "title":"Google", "description":"1. Search webpages, images, videos and more.", "image": "image1", "url": "url1" } then again some text { "title":"Google", "description":"2. Search webpages, images, videos and more.", "image": "image2", "url": "url2"} some text again';
var matches = text.match(re);
答
我不太清楚你想达到什么 - 我想你想捕获所有的JSON对象,所以正则表达式可能会有所帮助。现在我不是正则表达式的专家,这是一个超级快速入侵,但你可以解析字符串与
var str = YOUR _STRING_HERE;
// this is in no way fault tolerant
var rgx = /\{[^\}]*\}/g;
var jsons = [];
var match;
while ((match = rgx.exec(str)) !== null) {
jsons.push(match[0]);
}
// do something useful with your JSONs
console.log(jsons);
请你更具体一点,以便我们可以帮助你。 –
你知道你在jsons之间得到了什么文字吗? – karthikdivi
您是否尝试过使用正则表达式从字符串中提取JSON? – drjimmie1976