'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?
Solution 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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
