user1870400 user1870400 - 3 months ago 10
Node.js Question

How to convert a JSON into a Tree like object using node.js javascript?

How to convert a JSON into a Tree like object using node.js javascript? In Java we have a jackson library that converts a JSON into Tree object and I am trying to find something equivalent in JavaScript?

Answer

Unless your JSON contains a unicode line separator or paragraph separator it is already a subset of Javascript, and evaulating it as an expression will resolve to an object that is already a tree like data structure. Suppose you had the JSON in a file called config.json:

{ "test": { "foo": { "hello": "bob" }, "bar": { "world": "cloud" } } }

Then you can just include that as JavaScript, EG with require:

const config = require( './config.json' );

and config will be an object with one property (test), which itself is an object with two properties "foo" and "bar", which are both objects themselves (see how it is tree-like):

config.foo.hello === 'bob';

If you don't trust that the file actually contains the JSON you expect (suppose it was uploaded by a user), you can load the file into a string (which I'm assuming you already have), and then use JSON.parse to get the same object as the JSON evaluated to before.