0

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.

1 Answers1

0

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))
Rob Brander
  • 3,702
  • 1
  • 20
  • 33
  • Hi, Thank you. I got it. Can you help me to get the actual result as mentioned in the question. that is `{ "key1" : "val1", "key2" : "val2" }` But using this code I am getting `{ "key1" : ["val1"], "key2" : ["val2"] }`. Can you help me on this? – Abinash Biswal Apr 28 '20 at 15:17
  • I'm not familiar with the jsonpath library. However, given what you've shown as the result, you can fix this by changing `fire.query(obj, value)` to `fire.query(obj, value)[0]`. This accesses the content in the first array element – Rob Brander Apr 28 '20 at 15:36