我正在使用jQuery中的AJAX调用从API检索JSON对象。这是我回来的一个示例对象:
...
"batchcomplete": "",
"query": {
"normalized": [
{
"from": "star trek",
"to": "Star trek"
}
],
"pages": {
"1048985": {
"pageid": 1048985,
"ns": 0,
"title": "Star trek",
"extract": "<ul><li><b>From other capitalisation</b>: This is a redirect from a title with another method of capitalisation. It leads to the title in accordance with the Wikipedia naming conventions for capitalisation, or it leads to a title that is associated in some way with the conventional capitalisation of this redirect title. This may help writing, searching and international language issues.\n<ul><li>If this redirect is an incorrect capitalisation, then {{R from miscapitalisation}} should be used <i>instead</i>, and pages that use this link should be updated to link <i>directly</i> to the target. Miscapitisations can be tagged in <i>any namespace</i>.</li>\n<li>Use this rcat to tag <i>only</i> mainspace redirects; when other capitalisations are in other namespaces, use {{R from modification}} <i>instead</i>.</li>\n</ul></li>\n</ul>"
}
}
}
}
我有另一个JSON对象回来,看起来像这样:
{
"batchcomplete": "",
"query": {
"normalized": [
{
"from": "set",
"to": "Set"
}
],
"pages": {
"454886": {
"pageid": 454886,
"ns": 0,
"title": "Set",
"extract": "<p><b>Set</b> or <b>The Set</b> may refer to:</p>\n\n"
}
}
}
}
我尝试做的是搜索这些对象以寻找特定的字符串,以便对结果执行逻辑以检索我实际需要的数据。在第一个例子中,我想在“extract”值中找到“From other capitalization”,在第二个例子中,我想找到'可以引用:'。
有没有办法在特定的JSON对象中搜索特定的字符串并返回该字符串是否存在?
答案 0 :(得分:1)
对于你的具体情况,我会做这样的事情
function searchResponse(response, query){
// loop through the objects keys which appear to be different page numbers
for (const pageNum in response.pages){
// reference the actual page object
const page = response.pages[pageNum];
// test the extract against the query.
if (page.extract.indexOf(query) !== -1) {
return true;
}
}
return false;
}
然后,您可以使用您要查找的任何搜索词调用每个响应上的函数。 true
的结果意味着响应包含查询。但是,如果api返回多个页面,这将无效,因为它会搜索每个页面,return true
如果任何页面包含query
,这可能不是所需的结果。
答案 1 :(得分:0)
我希望这会对你有所帮助。使用普通的javascript迭代键并找到所需的对象。
var obj = {
"batchcomplete": "",
"query": {
"normalized": [{
"from": "set",
"to": "Set"
}],
"pages": {
"454886": {
"pageid": 454886,
"ns": 0,
"title": "Set",
"extract": "<p><b>Set</b> or <b>The Set</b> may refer to:</p>\n\n"
}
}
}
};
var searchStr = " may refer to";
var results = [];
Object.keys(obj.query.pages).forEach(function(key) {
if (obj.query.pages[key].extract.includes(searchStr)) {
results.push(obj.query.pages[key].extract);
}
});
results.forEach(function(res){ console.log(res); });