1

Sorry, I'm still new to programming, so please pardon me, I need help adding a new property inside a JSON file. :(

I want it to edit the JSON file~! meow~

animals.json: (Before Adding New Property)

{
  "cat": {
    "name": "Hiro",
    "age": 6
  },
  "wolf": {
    "name": "Kairo",
    "age": 3
  }
}

index.js (Example Code to add new Property)

var file = require('../../data/animals.json');

file["wolf"].push({gender: "female"})

the new animals.json after running index.js

{
  "cat": {
    "name": "Hiro",
    "age": 6
  },
  "wolf": {
    "name": "Kairo",
    "age": 3,
    "gender": "female"
  }
}

Is this possible? And if so, how? Thank you!

1 Answer 1

1

this should work

var file = require('../../data/animals.json');
const fs = require("fs");

file.wolf.gender = "female";

fs.writeFileSync("../../data/animals.json", JSON.stringify(file));

Using dot notation, you can either create or update property on a non null property.

Sign up to request clarification or add additional context in comments.

1 Comment

can you update your question to add this requirement? you need to use fs to overwrite the json file. let me see if I can update my answer.

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.