Add object to JSON with Node.js

Add object to JSON with Node.js



I have a JSON file that I need to use as a database to add, remove and modify users, I have this code:


'use strict';

const fs = require('fs');

let student =
id: 15,
nombre: 'TestNombre',
apellido: 'TestApellido',
email: 'TestEmail@gmail.com',
confirmado: true
;


let data = JSON.stringify(student, null, 2);
fs.writeFileSync('personas.json', data);



But that overwrites the JSON file, and I need to append as another object, so it continues with id 15 (last one was 14).



Here is a piece of the JSON file:



"personas": [

"id": 0,
"nombre": "Aurelia",
"apellido": "Osborn",
"email": "aureliaosborn@lovepad.com",
"confirmado": false
,

"id": 1,
"nombre": "Curry",
"apellido": "Jefferson",
"email": "curryjefferson@lovepad.com",
"confirmado": true
,
]



How can I do this?





Load the file first, keep it in memory and everytime you update that object you also store it back in the file.
– MinusFour
Aug 23 at 23:30





There are some nice node_modules that can do the fs stuff for you and make it seem like you are just dealing with data. One that comes to mind is lowdb.
– Mark Meyer
Aug 23 at 23:35





Is this a duplicate? stackoverflow.com/questions/36093042/…
– R01010010
Aug 23 at 23:49




2 Answers
2



Just require the file, push the student in the personas prop and
writeFileSync it back.


require


student


personas


writeFileSync


'use strict';

const fs = require('fs');

let current = require('./personas.json');
let student =
id: 15,
nombre: 'TestNombre',
apellido: 'TestApellido',
email: 'TestEmail@gmail.com',
confirmado: true
;

current.personas.push(student);

// Make sure you stringify it using 4 spaces of identation
// so it stays human-readable.
fs.writeFileSync('personas.json', JSON.stringify(current, null, 4));





why the sync? just curious
– R01010010
Aug 23 at 23:48





To match the OP's preferred method. He/She already uses fs. writeFileSync in the question code snippet.
– Nicholas Kyriakides
Aug 23 at 23:53



fs. writeFileSync





ah! ok, thought maybe it was really necesary :P
– R01010010
Aug 24 at 0:04





Thank you! This is exactly what I was looking for!
– Nachot93
Aug 24 at 0:06



every time you want to write to the JSON file, you’ll need to read it first/parse it, update he Object and then write it to disk.



There’s a popular solution already handling that. Checkout lowdb



For the autoindexing - I believe the documentation suggests ways some helper libraries for this module to make that happen



Don’t reinvent the wheel!






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)