0

I want to update by adding information to a json file that looks like

[{"name": "Nathan"},{"name": "Jeff"}]

I am currently doing this

const fs = require('fs');
let name = require('./test.json');

let data = JSON.parse(name);

data.push({name: 'Bob'});

name = JSON.stringify(data)

My desired result is to have the JSON file to look like this

[{"name": "Nathan"},{"name": "Jeff"},{"name": "Bob"},]

3 Answers3

1

your code doesn't change the file, it only changes the variable containing the value of the JSON file, and don't use JSON.parse you can require it directly to the variable, then work with it as a js object. if you want then to change the file, you can use the "fs" module in this answer ( and don't forget that it is asynchronous )

0

I'd suggest using the very handy lowdb module, it supports a lot of operations on simple JSON files.

Here's an example:

const dbFileName = "db.json";

const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')

const adapter = new FileSync(dbFileName)
const db = low(adapter)

// Set some defaults (required if your JSON file is empty)
db.defaults({ users: [] })
.write()

// Add some users and save..
db.get('users')
.push({ id: 1, name: 'Jack Smith', dob: '1981-21-08'})
.push({ id: 2, name: 'Kim Jones', dob: '1992-14-03'})
.write()

// Show users.
const userList = db.get('users').value();
console.log("Users: ", userList);

// Find a user
console.log("Find user by name:", db.get('users').find({ name: 'Kim Jones' }).value());

There are others on the module page.

Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
0

first: It is not fs needed to import a json file. simply :

let data = require('filename.json');

or import it if you are using BABEL.

About the string part, you can use substr like this:

let data = [{"name": "Nathan"},{"name": "Jeff"}];

data.push({name: 'Bob'});

let name = JSON.stringify(data)
name=`${name.substr(0,name.length-1)},]`;

console.log(name);
Vahid Alimohamadi
  • 4,900
  • 2
  • 22
  • 37