0

I would like to store JSON in a textfile. Using:

let obj = {'column':empty,'ppas':ppa}; 
await myFunctions.addToStorage(obj);

async function addToStorage(obj) {
  const fs = require("fs");
  fs.readFile("storage.json", function (err, data) {
    var json = JSON.parse(data);
    json.push(obj);
    fs.writeFile("storage.json", JSON.stringify(json), function (err) {
      if (err) throw err;
      console.log('The "data to append" was appended to file!');
    });
  });
}

storage.json contains:

{"column":"0:lubbock:LW2-4$","ppas":[{"ppa":50000,"url":"/"},{"ppa":51724.137931034486,"url":"/lubbock"}]}

when I run the program I get:

  json.push(obj);
         ^
  TypeError: json.push is not a function
    at /home/....functions.js:5:10

I can see that, the problem is that the I'm trying to stored item in storage.json is a stringified object not a stringified array of objects.

How do I set up the project so for the first object you create an array (like if storage.json does not exist)and subsequent objects are added to the array. Is there a commonly used approach to this?

3
  • Initialize the file with an empty array []. Commented Mar 24, 2022 at 20:56
  • 1
    Are you expecting an array? Because the file contains an object, not an array. Maybe you mean json.ppas.push? Commented Mar 24, 2022 at 20:58
  • @Barmar - your way worked! Commented Mar 25, 2022 at 13:47

1 Answer 1

1

You're trying to push items onto an object, not an array

Your code correctly converts the string to a javascript object, but you can't push() to it because objects are not arrays*, and don't have a push() method. Your object does contain an array of ppas, though.

You don't say what "array" you actually want, or what it's supposed to contain, so here's some guesses:

Add to the array inside the json object

If you're trying to add ppa objects to the "ppa" array, you need to push to that instead: replace json.push(obj) with json.ppas.push(obj). You don't show us where the ppa variable on the first line comes from, but it also needs to be an array.

Add keys to the object

If you're trying to add another single non-ppa object to the root json object, you need to put it under a different key: change addToStorage(obj) to addToStorage(key, obj), where key is some string, and add it with json[key] = obj.


* However, arrays are objects

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.