Search code examples
javascriptjsonpath

How to fetch a specific object from JSON using JSONPATH by putting the local variable in query string?


I am exploring about JSONPATH. And I used it in JS to fetch some specific data from the parent JSON.

Let's say the JSON object that I have is,

var JSON_OBJECT = {
  "data" : [
      {
          "firstname" : "abn",
          "Lastname" : "Bis"
      },
      {
          "firstname" : "abh",
          "Lastname" : "Bis"
      },
      {
          "firstname" : "pqr",
          "Lastname" : "mno"
      }
  ]
}

And I would like to fetch the Objects whose Lastname is "Bis". Then this is my code to fetch those objects.

var fire = require('jsonpath')

var s = "$.data[?(@.Lastname == 'Bis')]"

console.log(fire.query(JSON_OBJECT, s))

So my question is if I store "Bis" in a variable. Then how to write the same query to get those objects?

This is what I have tried.

var dataToBeFound = "Bis"
var s = `$.data[?(@.Lastname == ${dataToBeFound})]`
console.log(fire.query(JSON_OBJECT, s))

This gives me an empty array.


Solution

  • Your query will not run properly because of string concatenation. By adding a string variable in Template String you will effectively turn it into a single string and lose the double quotes " ". So you'll need to specifically insert the double quotes as part of the value of the string.

    See this example to see how your string turns out.

    var dataToBeFound = "Bis"
    var s = `$.data[?(@.Lastname == ${dataToBeFound})]`
    
    console.log(s)

    So, you see that you are missing the double quotes in the search expression which breaks the expression. You can tackle this with either string escaping or use a Template Literal ` ` to insert a value with " " around it.

    The example below shows you how your value is being output and should work for your JSONPATH query.

    var dataToBeFound = `"Bis"`;
    var s = `$.data[?(@.Lastname == ${dataToBeFound})]`;
    
    console.log(s)