Javascript - Appending object to JSON File - javascript

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.

Related

How to convert a list that is a string into a list in Javascript?

I am trying store data in a .txt file, and then convert it back in to a Javascript list, or array, whatever you call it.
Data in txt file:
[{ firstName: "John", lastName: "Carpenter" },
{ firstName: "Dav", lastName: "Douglas" }]
Then I am trying to make it a list variable:
// my variable
var people = []
// read data from txt file
fs.readFile("./data/data.txt", "utf-8", (err, data) => {
if (err) { console.log(err) }
console.log(data, typeof(data));
people = data
})
Is there a way to convert it from a string to an array?
This is a bad solution, but ONLY if you can't change the format of your input, it might be workable, but be sure you never, ever have user input or foreign input like webrequests in the file, as it will be executed as javascript.
Do not use it unless you know what you are doing!
var data = '[{ firstName: "John", lastName: "Carpenter" },{ firstName: "Dav", lastName: "Douglas" }]'
var people = eval(data)
console.log(people);
body {
background : red;
color: white;
margin-top:0px;
padding-top:0px;
}
h1 {
margin-top:0px;
padding-top:0x;
}
<marquee><blink><h1>EVAL IS EVIL - EVAL IS EVIL - EVAL IS EVIL - EVAL IS EVIL - EVAL IS EVIL</h1></blink></marquee>
WHAT YOU WANT TO USE
Make sure the contents of the file is proper JSON. At this moment it isn't. When generating the file with javascript use JSON.stringify on the variables/arrays you wish to write to the file.
The data will then change to
[{ "firstName": "John", "lastName": "Carpenter" },
{ "firstName": "Dav", "lastName": "Douglas" }]
And then you can use JSON.parse() to decode the data from the file.
var data = '[{ "firstName": "John", "lastName": "Carpenter" },{ "firstName": "Dav", "lastName": "Douglas" }]'
var people = JSON.parse(data);
console.log(people);

Add new property to JSON file key using NodeJS

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.

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

How to parse/filter data from JSON file in Javascript

Is there any way to parse/filter the data present in JSON file in a Javascript file.
Basically, I am calling JSON file into my local javascript. I am having trouble in reading specific data and printing.
Can anyone please help.
JSON file contains:
{
"Data": [
{
"name": "John",
"age": 30
},
{
"joined on":"Jan 2015",
"working on": "Automation",
}
]
}
I am trying to read the above JSON file as:
var jfile = require("./Example.json");
var test = JSON.parse(JSON.stringify(jfile))
console.log(test)
I get the output like this:
{ Data:
[ { name: 'John', age: 30 },
{ 'joined on': 'Jan 2015', 'working on': 'Automation' } ] }
From the above, I am interested in accessing/filtering out only one i.e. "name". I would like to print only the value "John" to the console.
I have tried to use the ".filter" method to the JSON.parse method but it throws me an error as:
JSON.parse(...).filter is not a function
Is there any way to perform this activity?
You can access it using . dot notation
var a = {
"Data": [{
"name": "John",
"age": 30
},
{
"joined on": "Jan 2015",
"working on": "Automation",
}
]
}
console.log(a.Data[0].name)
filter is an array method.
JSON.parse(...) will not give you an array. It will give you an object with a Data property. The value of that property is an array.
JSON.parse(...).Data.filter.
You can't just ignore parts of your data structure.
If you have multiple items in your array of different shapes, you can use this
Access the Data key with json.Data
map your array to transform its items into names
apply filter(Boolean) to take out those who are undefined
In your case you'll end up with an array containing only one name John
const getName = json => json.Data.map(x => x.name).filter(Boolean);
const json = {
"Data": [{
"name": "John",
"age": 30
},
{
"joined on": "Jan 2015",
"working on": "Automation",
}
]
};
console.log(getName(json));
Your JSON's main level is an object (not an array) and only arrays have .filter method.
So filter the array under Data key:
var test = JSON.parse(JSON.stringify(jfile)).Data.filter(/*something*/);
But better if you aren't re-parse JSON:
var test = jfile.Data.filter(/*something*/);
As Quentin mentioned in his comment, What is the use of below statement ?
var test = JSON.parse(JSON.stringify(jfile))
You can directly access the name property from the response.
Try this :
var obj = {
"Data": [{
"name": "John",
"age": 30
},
{
"joined on": "Jan 2015",
"working on": "Automation"
}
]
};
// Solution 1
console.log(obj.Data.map(item => item.name).filter(Boolean));
// Solution 2
console.log(obj.Data.filter(item => item.name).map(elem => elem.name));

Get specific values form JSON Table with javascript over IDs

I have the following problem:
I have a JSON table with the data I need (found this on the internet since it is nearly what I need)
var testext ={"key1":[
{
"firstName":"Ray",
"lastName":"Villalobos",
"joined":2012
},
{
"firstName":"John",
"lastName":"Jones",
"joined":2010
}
]}
document.getElementById("demo").innerHTML=testext.key1[0].firstName;
This works fine but as you can see I still need an index [0] to get to the dataset I need.
I need to to this without this index...
like this here:
var testext = {
"key1": ["string1/1", "string1/2" ],
"key2": ["string2/1", "strin2/2"]
};
document.getElementById("demo").innerHTML = testext['key1'][0];
just combined so my variable would be something like :
document.getElementById("demo").innerHTML = testext['key1'].['firstname'];
Anyone an idea on how I can do this?
Thanks in advance.
You are almost correct. Restructure your array into an associative array of associative arrays. You can call them by array_name['first_index']['second_index'].
var testext = {
"key1": {
"firstName": "Ray",
"lastName": "Villalobos",
"joined": 2012
},
"key2": {
"firstName": "John",
"lastName": "Jones",
"joined": 2010
}
};
document.getElementById("demo").innerHTML = testext['key1']['firstName'];
<div id="demo">Default</div>

Categories