Processing a JSON file using JSONata in Node.JS returns undefined. Why is this happening?
I tried this but it's returning "undefined"
index.js
const jsonata = require("jsonata");
const fs = require("fs");
(async () => {
const json = fs.readFileSync("test.json", {encoding:'utf8', flag:'r'});
const expression = jsonata('V1.fields');
const result = await expression.evaluate(json);
console.log(result);
})()
test.json
[
12345,
{
"V1": {
"fields": {
"id": 0
}
}
}
]
output
% node index.js
undefined
https://try.jsonata.org/N02gm7EYz
CodePudding user response:
Despite its name, jsonata doesn't evaluate JSONs, it evaluates objects. You need to parse the JSON being read before passing it to jsonata.
You could do this explicitly:
const json = JSON.parse(fs.readFileSync("test.json", {encoding:'utf8', flag:'r'}));
But to be honest, it's easier to just require
it and let Node.js do the "heavy" lifting:
const json = require("./test.json");