jsonflex
A JSON stringifier and parser than handles and restores circular references and as well as class instances.
Installation
npm install jsonflex
Then in your node.js application:
const flexjson = ; // And: If you want to use flexjson on frontend// you can serve it as Express middlewareconst express = ;const app = ;app;
Options
There are four options you can change if you want to. Add any or all of them when requiring flexjson. Below they are listed with their default values:
const flexjson = jsonDir: '/www/json' // directory on server to save json to scriptUrl: '/jsonflex.js' // url to load clientside script from saveUrl: '/json-save' // url used by jsonflex to save json loadUrlPrefix: '/json/' // prefix to add to clientside load url );
Include clientside
Include the script clientside like this:
Note: For non-Node.js users... If you want to use this script clientside only (without Node.js) you can do so:
- Locate jsonflex.js-file in the repository, load only this file and note that JSON._save won't work out of the box.
API
JSON._save(filename, data, [, replacer[, space]])
Saves JavaScript data to a file after parsing it to JSON using JSON._stringify. Returns a promise.
Example
let persons = name:'Anna' name: 'Bob' name: 'Cecilia';JSON;
Or with await syntax inside an async function:
let persons = name:'Anna' name: 'Bob' name: 'Cecilia';await JSON;console;
JSON._load(filename [, reviver])
Loads JSON from a file and parses it to JavaScript data using JSON._parse. Returns a promise.
Example
JSON;
Or with await syntax inside an async function:
let persons = await JSON;console;
Note: When used on the clientside JSON._load actually takes an URL rather than a file path as its argument.
JSON._classes(...classes)
Registers class definitions so that JSON._stringify and JSON._parse knows about them and can revive object instances created from classes.
Example
// Earlier in your code you have defined the classes Person and PetJSON;
JSON._stringify(data [, replacer[, space]])
Works just like the normal JSON.stringify but translates circular references to JSON paths and (optionally, see JSON._classes) "stamps" every object created from a class with its class name.
Example
const flexjson = ; { thisname = name; thispets = pets; forlet pet of pets petowner = this; } { return `Hi! I am !` } { thisname = name; thisowner = owner; } { return `Hi! I am ! My owner is !`; } JSON; let pets = 'Fido' 'Garfield' 'Chili'; let persons = 'Anna'pets0 pets1 'Bob' pets2; let json = JSON; console;
The contents of the variable json would now be:
JSON._parse(data [, reviver])
Works just like the normal JSON.parse but translates JSON paths to circular references and (optionally, see JSON._classes) revives object instances.
Example
Given that we have the JSON from the JSON._stringify-example we can now revive it like this:
JSON; let personsRevived = JSON; console;// => Hi! I am Garfield! My owner is Anna!