Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

353
Views
TypeError: json.push is not a function while addending json objects

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!