0

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.

1
  • 3
    Try changing items["item"].push(str); to items["items"].push(str); Commented Feb 28, 2021 at 12:21

1 Answer 1

1

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.

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.