我将以下json字符串作为变量jsonString。
[
{
"id":1,
"created_at":"2016-12-01 12:28:52",
"updated_at":"2016-12-01 13:02:49",
"title":"Company 1",
"text":null,
"url":"http:\/\/somesite.co.uk\/",
"is_active":1,
"api":"309809458909",
"list":"343242344344"
},
{
"id":2,
"created_at":"2016-12-01 12:59:51",
"updated_at":"2016-12-01 12:59:51",
"title":"Company 2",
"text":null,
"url":"http:\/\/secondsite.co.uk/",
"is_active":1,
"api":"309809809809",
"list":"890890809809"
}
]
我想通过url匹配,然后返回该ID中的数据。
因此,搜索http://secondsite.co.uk将返回该特定对象中的所有数据。
我尝试了以下但不确定这是否可行。 (基于https://gist.github.com/iwek/3924925#file-find-in-json-js)
//return an array of keys that match on a certain value
function getKeys(obj, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getKeys(obj[i], val));
} else if (obj[i] == val) {
objects.push(i);
}
}
return objects;
}
var json = jsonString;
var js = JSON.parse(json);
//example of grabbing keys by searching via values in JSON
console.log('06' + getKeys(js,'http://secondsite.co.uk/'));
但它并没有返回结果。有没有比这更好的了?