How to fix creating a new object in JSON file?

SadlerJ

I'm trying to create a function that when called will update a specific object in json file. However, it updates the object as well as creating a new one.

I've tried many different methods in trying to get this to work, but all have failed. The closest I've got to it working is the code shown below, but it still doesn't do what is required.

This is my function:

var fs = require('fs');
var _ = require("underscore");

module.exports = {
  personalUpdate: function (id, forename, surname, dob, gender, callback) {    
    let rawdata = fs.readFileSync('data.json');
    let data = JSON.parse(rawdata);
    let filtered = _.where(data['students'], { id: id });
    let all = filtered[0];

    all.forename = forename;
    all.surname = surname;
    all.dob = dob;
    all.gender = gender;

    data["students"].push(all);

    fs.writeFileSync('data.json', JSON.stringify(data, null, 2), (err) => {
      if (err) throw err;
    });
    callback("success");

  }
}

And this is the JSON file that I want to update:

{
  "teachers": [
    {
      "name": "",
      "email": "",
      "password": "",
      "formGroup": "",
      "id": ""
    }
  ],
  "students": [
    {
      "surname": "test",
      "forename": "test",
      "dob": "",
      "homeAddress": "",
      "homePhone": "",
      "gender": "",
      "tutorGroup": "",
      "schoolEmail": "",
      "grades": [
        {
          "french": 8,
          "maths": 7
        }
      ],
      "id": ""
    },
    {
      "surname": "test2",
      "forename": "test2",
      "dob": "",
      "homeAddress": "test2",
      "homePhone": "",
      "gender": "",
      "tutorGroup": "",
      "schoolEmail": "",
      "grades": [
        {
          "french": 9,
          "maths": 8
        }
      ],
      "id": ""
    }

  ]
}

I had to remove and change the objects and info inside them, as it contained confidential information.

When running this function, it finds the object that is specified in the parameter. It then updates that object, but it then creates another object at the bottom of the original JSON object, which it is not supposed to.

Also, is there a better way to update the specific objects in the JSON file?

Daniel Abrão

tl;dr

  1. The result set is duplicating because you are pushing it into the array
  2. The change is being applied due to the variables holding the same object reference, so they are being mirrored across objects that share the same pointer.

Explanation

It creates a new one due to the data["students"].push(all); instruction.

When you manipulate objects in javascript you need to be aware of how the reference between them work, so you can avoid bugs and use them in your benefit.

For example, take this set of instructions:

let a = {"x": 1};
let b = a;
b.x = 3;
console.log(a) // it will output {"x": 3}

Notice that we:

  1. Create an object with the prop x equal 1 and assign it to the variable a
  2. Initialize a variable b with the value of a
  3. Change the property x on the variable/object b
  4. Then we can observe that the change was also reflected in the variable a, due to the object reference.

So, basically this is exactly what is happening with your instructions when you do all.forename = forename; it changes the variable all, but also the original object which it derives from.

Here is a nice reference that explains this concept more in-depth

@EDIT

I strongly advise you not using the sync version of functions like readFileSync since this blocks the event loop. Here is the official guidelines about it

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to fix a not creating file

Update same object in a JSON file without creating a new object inside it

How to fix: Delete duplicates in a JSON file and write to a new one

Adding two JSON object and creating new one

how to update the file without creating new file

How to fix file .json not found

How to push a new object into a JSON file using PHP

How can I add a new object to a list of objects in a .json file?

How to fix " AttributeError: 'int' object has no attribute 'replace' " while replacing and writing to a new file?

Creating JSON object from language file

How to cast while creating a new object in typescript?

Concatenate multiple files into a single file object without creating a new file

How to fix "failed to create template" when creating new dotnet project?

How to Add New Line Feed while creating JSON file via VB.NET?

How to fix Git error: object file is empty?

How to fix false array of object JSON?

How to fix unset json object in php

Creating a new user in Django returns: "Object of type Users is not JSON serializable"

Defining new field in JSON Schema for creating 2 view of an object

Creating an object: with or without `new`

Java creating new object

Creating new object in loop

Creating a new object, not a reference

Creating a JSON object with name of the JSON file and its content in bash

Adding a new JSON Object to a file array

how to map a json object into another new object

How to add a new JSON object in an existing JSON file using jq and variable arguments

how to fix file .json not found when it is there

How to fix failed to locate file json in Swift