P
P
perSeR2021-02-04 23:37:47
JavaScript
perSeR, 2021-02-04 23:37:47

How to add object to json file?

In general, I want to send

[
{
"id": 1
}
]

I tried to file ikuky.json through myJson.push, it doesn't work.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
Tim, 2021-02-05
@perSeR

You need to overwrite the file
https://nodejs.org/api/fs.html
https://metanit.com/web/nodejs/2.8.php

const Json = require('./my.json');
const fs = require("fs");
Json.push({
    userId: 2,
    id: 2
});
fs.writeFileSync("my.json", JSON.stringify(Json))

A
Arthur Sh, 2021-02-04
@Shev_Art_V

If this is a file, then you must first read it, then convert the string to JSON, and only then work with it.

A
Alexander, 2021-02-04
@Aleksandr-JS-Developer

You need to parse the string, add the required value, and cast it back to JSON
Links:
JSON format, toJSON method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question