Edit a json file with ease.
$ npm i edit-json-file
"use strict";
const editJsonFile = require("edit-json-file");
// If the file doesn't exist, the content will be an empty object by default.
let file = editJsonFile(`${__dirname}/foo.json`);
// Set a couple of fields
file.set("planet", "Earth");
file.set("city\\.name", "anytown");
file.set("name.first", "Johnny");
file.set("name.last", "B.");
file.set("is_student", false);
// Output the content
console.log(file.get());
// { planet: 'Earth',
// city.name: 'anytown',
// name: { first: 'Johnny', last: 'B.' },
// is_student: false }
// Save the data to the disk
file.save();
// Reload it from the disk
file = editJsonFile(`${__dirname}/foo.json`, {
autosave: true
});
// Get one field
console.log(file.get("name.first"));
// => Johnny
// This will save it to disk
file.set("a.new.field.as.object", {
hello: "world"
});
// Output the whole thing
console.log(file.toObject());
// { planet: 'Earth',
// name: { first: 'Johnny', last: 'B.' },
// is_student: false,
// a: { new: { field: [Object] } } }
- String
path
: The path to the JSON file. - Object
options
: An object containing the following fields: stringify_width
(Number): The JSON stringify indent width (default:2
).stringify_fn
(Function): A function used byJSON.stringify
.stringify_eol
(Boolean): Wheter to add the new line at the end of the file or not (default:false
)autosave
(Boolean): Save the file when setting some data in it.
- JsonEditor The
JsonEditor
instance.
Set a value in a specific path.
- String
path
: The object path. - Anything
value
: The value.
- JsonEditor The
JsonEditor
instance.
Get a value in a specific path.
- String
path
:
- Value The object path value.
Remove a path from a JSON object.
- String
path
: The object path.
- JsonEditor The
JsonEditor
instance.
Read the JSON file.
- Function
cb
: An optional callback function which will turn the function into an asynchronous one.
- Object The object parsed as object or an empty object by default.
write Write the JSON file.
- String
The
: file content. - Function
cb
: An optional callback function which will turn the function into an asynchronous one.
- JsonEditor The
JsonEditor
instance.
Empty the JSON file content.
- Function
cb
: The callback function.
Save the file back to disk.
- Function
cb
: An optional callback function which will turn the function into an asynchronous one.
- JsonEditor The
JsonEditor
instance.
- Object The data object.
Edit a json file.
- String
path
: The path to the JSON file. - Object
options
: An object containing the following fields:
- JsonEditor The
JsonEditor
instance.
Have an idea? Found a bug? See how to contribute.
See the LICENSE file.