Jeff Swearingen Jeff Swearingen - 13 days ago 6
Ajax Question

How to search a JSON object for a specific string within the object using jquery

I am retrieving JSON objects from an API using AJAX calls in jQuery. This is an example object that I am getting back:

...
"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>"
}
}
}
}


I have another JSON object coming back that looks like this:

{
"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"
}
}
}
}


What I am attempting to do is search these objects for specific strings in order to perform logic on the results to retrieve the data I am actually looking for. In the first example, I want to find 'From other capitalisation' in the "extract" value, and in the second example, I want to find 'may refer to:'.

Is there a way to search a specific JSON object for a specific string and return whether that string is present or not?

Answer

For your specific case, I would do something like this

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

Then you'd invoke the function on each response with whatever search term you are looking for. A result of true would mean that the response contained the query. However, this would not work if the api returned multiple pages because it would search through each page and return true if ANY of the pages contained the query, which might not be the desired results.

Comments