Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

357
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda