lightyears99
lightyears99

Reputation: 111

error when using "push()" to add string to JSON array

I want to add strings to my JSON file which looks like this:

{
    "items": []
}

which is required like this: var items = require("../../config/item.json");

Then I am writing it to the array like this: items["item"].push(str);,

which triggers an error: Cannot read property 'push' of undefined

How can I add the string "str" to the array?

After pushing it, i write it to the file like this:

let data = JSON.stringify(items);

fs.writeFileSync("../../config/item.json", data, (err) => {
    if (err) {
      throw err;
    } else {
      console.log("item written successfully.");
    }
  });

Thanks in advance.

Upvotes: 0

Views: 343

Answers (1)

Brettski
Brettski

Reputation: 20091

You need to use the push() method on the array, your property selector ['item'] doesn't exist it's ['items']. The json file itself is not an array, it's an object.

To push in to the array:

var items = require("../../config/item.json");
items.items.push(str);

Or you can do items['items'].push(str) where ['items'] is a property selector.

Upvotes: 1

Related Questions