简体   繁体   中英

Working with json array in files in JavaScript for loading, saving, update data?

Basically, this shouldn´t be a very difficult question, but I´ve tried for like 2 or 3 hours and couldnt reach my goal, especially for such an "easy" question. Im using Node.js and my goal is, to load data from a Json file into a variable, add some new data to this and store my data into the same json file again.

Herefor, my json file looks like this:

[
    {
        "name": "Max",
        "date": "1.1.2020"
    }, {
        "name": "Henry",
        "date": "2.2.2020"
    }
]

Here´s my code:

const fs = require('fs');
const filename = './jsonFile.json';
const data = loadJSON();
// console.log(data) keeps saying undefined (whithout using .toString in loadJSON)

function loadJSON() {
    JSON.parse(fs.readFileSync(filename).toString); // toString doesnt work
}

function saveJSON(data) {
    fs.writeFileSync(filename, JSON.stringify(data));
}

function adduser(username) {
    var today = "3.3.2020"; // doesnt matter

    let obj = {
        name: username, 
        date: today
    }

    vipJson.push(obj);
    saveVIP(vipJson);
}

It doesnt seem to be working. Could anyone help me, to fix my problem, so I can work with .json files ? Thanks a lot!

If you are sure about json files, you can read data from file using require.

const fs = require('fs');
const filename = './jsonFile.json';
const data = loadJSON();

function loadJSON() {
    return require(filename)
}

function saveJSON(data) {
    fs.writeFileSync(filename, JSON.stringify(data));
}

function adduser(username) {
    var today = "3.3.2020"; // doesnt matter

    let obj = {
        name: username, 
        date: today
    }

    data.push(obj);
    saveJSON(data);
}

Try above code snippet.

You need to specify the BufferEncoding options to read the file, something like this.

const fs = require("fs")
const data = fs.readFileSync("./myfile.json", { encoding: "utf8", flag: "r" })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM