Skip to content
Advertisement

Appending array to JSON file with JavaScript

Now I dont have any other choise. Everything seems right in my eye. Still not working.

I am doing little food app for myself to get know how much i’ve eaten. I created JSON file named ruoat.json, where I going to add foods via app. I have done this earlier with PHP and it was quite easy. But now doing this with JavaScript gives me a gray hair.

Tried few different ways find from Google, no any working solution.

Where is the problem?

function addfood() {

    const food_name = document.getElementById('food-name').value;
    const food_prot = document.getElementById('food-prot').value;
    const food_badfat = document.getElementById('food-badfat').value;
    const food_fat = document.getElementById('food-fat').value;
    const food_carbs = document.getElementById('food-carbs').value;
    const food_salt = document.getElementById('food-salt').value;


    var json_array = '{"name": "' + food_name + '","prot": '+ food_prot + ',"badfat": ' + food_badfat + ',"fat": ' + food_fat + ',"carbs": ' + food_carbs + ',"salt": ' + food_salt + '}';

    // var json_push = JSON.parse(json_array); // Muuntaa stringin JSON objektiksi


    const fs = require("fs");
    let ruokalista = fs.readFileSync("../json/ruoat.json","utf-8"); // Read JSON file

    let ruoka = JSON.parse(ruokalista); // JSON file -> Array

    ruoka.push(json_array); // Add object json_array to array ruoka

    ruokalista = JSON.stringify(ruoka); // Array back to JSON

    fs.writeFileSync("../json/ruoat.json",ruokalista,"utf-8"); // Save modified JSON file

}

Advertisement

Answer

I can see that you are using the fs module, which is a part of Node.js. Nodejs does not support the document object because it is designed to be run outside a browser. That aside, it would work if you didn’t do the file business and ran it in a browser

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement