Search code examples
node.jsjsonpath

How to apply jsonpath query to get the object?


The question in detail is, I have a node js code 'app.js'


var fire = require('jsonpath')
let Config = JSON.parse(fs.readFileSync('./config.json', 'utf-8'))

var obj = {
    "key1" : "val1",
    "key2" : "val2",
    "key3" : "val3",
    "key4" : "val4",
    "key5" : "val5"
}

console.log(fire.query(obj, ?))

and a config.json file

{
    "result" : {
        "key1" : "$.key1",
        "key2" : "$.key2"
    }
}

So from here I would like to fetch the result key from config.json file using the jsonpath query where the object I would like to work on is obj mentioned in app.js

And the output I am looking for is

{
    "key1" : "val1",
    "key2" : "val2"
}

I don't want to get this object by witing separate query for each keys, like to get key1 I could write result['key1'] = fire.query(obj, '$.key1')

Instead I'd like to query in single line to get the complete result object.

This is what I have tried so far.


Solution

  • You have a config, that has many keys, and each key has a value that represents a path to a value inside an object. So the first thing you need to do is iterate over each of the key/value pairs in the results config object. For each one, you'll need to call the jsonpath function using the value at that pair. I assume the key of the pair will represent the key in the result, and the value of the result will be what jsonpath returns.

    // Given 'obj' and 'Config' exist...
    const result = Object.entries(Config.result)
      .reduce((resultObj, [key, value]) => (
        { ...resultObj, [key]: fire.query(obj, value) }
      ), {})
    
    console.log(JSON.stringify(result, undefined, 2))