Add new property to JSON file key using NodeJS - javascript

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!

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.

Related

unable to replace a part of json value using fs javascript

this is my js code
let content019 = JSON.parse(require("fs").readFileSync("./settings.json"));
// edit or add property
content019.api.client.locations[1] = 999999999999;
//write file
fs.writeFileSync('settings.json', JSON.stringify(content019,null ,2));
i tried using content019.api.client.locations[1] but it changed the inner part to "1": "999....
this is a part of my json file
"1": {
"name": "Germany",
"type": null
},
"2": {
"name": "Singapore",
"type": null
}
},
i want it to only change "1": { to "999999999999": {
even tried content019.api.client.locations.1, didnt work. received error unexpected number
you have to use a string, not a number index. Since your json is invalid, I can only assume that the first part is ok, so you can try
content019.api.client.locations["1"] = 999999999999;
or maybe
content019.api.client.locations["999999"] = content019.api.client.locations["1"];
delete content019.api.client.locations["1"];

Cypress cy.write push new items to an array throws "push is not a function" error

Using the same code from https://docs.cypress.io/api/commands/writefile.html#Flags
const filename = '/path/to/list.json'
cy.readFile(filename).then((list) => {
list.push({ item: 'example' })
// write the merged array
cy.writeFile(filename, list)
})
#system throws:
list.push is not a function
fixture file:/path/to/list.json
{
"details": {
"name": "abc",
"age": 20
}
}
expecting the list.json output as
{
"details": {
"name": "abc",
"age": 20
},
"item": "example"
}
Has anyone tried to append an existing JSON file with the above code snap?
If so please share with me your experience.
Thanks
.push() is for arrays, but you have an object in your JSON file. Use list.item ='example'; to set a new property on an object.

Adding a variable name to a JSON list?

I'm writing this in Python and I want to be able to modify this JSON file
from this,
{
"name": "UVIDOCK",
"date": "03/14/2018",
"cola": "18:18:00",
"colb": "6.70000"
}
to this
window.data = {
"name": "UVIDOCK",
"date": "03/14/2018",
"cola": "18:18:00",
"colb": "6.70000"
}
Appreciate the help in advance.
So do you want a string with your JSON and a variable name? Assuming yes, but keeping in mind that it will not be a valid JSON, the solution will be:
import json
data = { "name": "UVIDOCK", "date": "03/14/2018", "cola": "18:18:00", "colb": "6.70000" }
jsonString = "window.data = " + json.dumps(data)
print (jsonString)
## Output: window.data = {"name": "UVIDOCK", "date": "03/14/2018", "cola": "18:18:00", "colb": "6.70000"}

How to fix creating a new object in JSON file?

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?
tl;dr
The result set is duplicating because you are pushing it into the array
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:
Create an object with the prop x equal 1 and assign it to the variable a
Initialize a variable b with the value of a
Change the property x on the variable/object b
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

Javascript - Appending object to JSON File

I currently have an object:
var obj = {
username: "James",
surname: "Brandon",
id: "[2]"
}
and I want to append it to "users.json":
[
{
"username": "Andy",
"surname": "Thompson",
"id": [0],
},
{
"username": "Moe",
"surname": "Brown",
"id": [1]
}
]
Do you know how I might be able to do this?
Thanks in advance.
This answer is assuming that you are working under Node.js.
As I understand your problem you need to solve a few different programming questions.
read and write a .json file
const fs = require("fs");
let usersjson = fs.readFileSync("users.json","utf-8");
transform a json string into a javascript array
let users = JSON.parse(usersjson);
append an object to an array
users.push(obj);
transform back the array into a json string
usersjson = JSON.stringify(users);
save the json file
fs.writeFileSync("users.json",usersjson,"utf-8");
If your code is running in the browser and users.json is an output file, I guess you already have access to its content.
Use the push() method.
Also, note the missing commas in your objects.
var obj = {
username: "James",
surname: "Brandon",
id: "[2]"
};
var users = [
{
"username": "Andy",
"surname": "Thompson",
"id": [0]
},
{
"username": "Moe",
"surname": "Brown",
"id": [1]
}
];
users.push(obj);
console.log( JSON.stringify(users) );
Now that you have the updated array of objects you can upload it to the server (check this question) or offer a download to the user (check this other question).
As you have been already told, there is no way to directly update client-side a file in the server. It is also not possible to save it directly into the client filesystem.

Categories