Edit json in js/node.js? - javascript

I am working on an nodejs app which reads data from a json file. Now I want to edit this json file in js (write to it). How do I do this ?
Here is my js code: `
var fs = require("fs")
//function for file input
function getFile(filename) {
var data = fs.readFileSync(filename,"ascii")
return data }
//parsing json
var jsonString = [getFile("File.json")]
var jsonObj = JSON.parse(jsonString)`

Modify the jsonObj as you want, create a new object or whatever, then write the file:
fs.writeFileSync("File.json", jsonData);
This will overwrite the file if it exists, so that way you edit the file.

You can load a json file by requiring it.
var contents = require('/path/to/file.json');
Iterate contents just like a regular object.

A JSON object, when parsed is, like any other JS object. Use object dot notation to access any data you want.
For example a value:
console.log(isonObi.something.value)
For example a value in an array:
console.log(isonObi.something[0].value)
From eyp
Modify the jsonObj as you want, create a new object or whatever, then write the file:
fs.writeFileSync("File.json", jsonData);
This will overwrite the file if it exists, so that way you edit the file.

With nodeJS, you can require a JSON file.
Supposing you get this JSON file :
//test.json
[
{
"name": "toto",
"code": "4"
},
{
"name": "test",
"code": "5"
}
];
Then, you can require this file and perform some modification :
var json = require('./test.json');
json.forEach(function(elm){
elm.name = 'test';
});

Related

Remove data array JS

I am working on creating a file where data can be read from a JSON file.
I can add new names to the file but I am unable to delete. When I enter a name to delete it actually adds the name to the file.
Why is it adding & not deleting? The objective is to be able to delete a specific name from the list that will be generated.
Thank you in advance! Here is my code with comments on what I am attempting to do.
// POST request to add to JSON & XML files
router.post('/post/json', function(req, res) {
// Function to read in a JSON file, add to it & convert to XML
function appendJSON(obj) {
// Read in a JSON file
var JSONfile = fs.readFileSync('Staff.json', 'utf8');
// Parse the JSON file in order to be able to edit it
var JSONparsed = JSON.parse(JSONfile);
// Add a new record into country array within the JSON file
JSONparsed.member.push(obj);
// Beautify the resulting JSON file
var JSONformated = JSON.stringify(JSONparsed, null, 4);
// Delte a specific entry from JSON file
var i = member.indexOf(" ");
if (i != -1) {
member.splice(i,1);
}
// Write the updated JSON file back to the system
fs.writeFileSync('Staff.json', JSONformated);
// Convert the updated JSON file to XML
var XMLformated = js2xmlparser.parse('staff', JSON.parse(JSONformated));
// Write the resulting XML back to the system
fs.writeFileSync('Staff.xml', XMLformated);
}
// Call appendJSON function and pass in body of the current POST request
appendJSON(req.body);
// Re-direct the browser back to the page, where the POST request came from
res.redirect('back');
});
Here is an example of the JSON file
{
"member": [
{
"Full_Name": "",
"Address": "",
"Gender": "",
"Phone_Number": ""
}
]
}
The splice function removes the item from the array and returns the deleted item. So if you want to delete an item by an attribute from your JSON like Full_Name you have to find the index of the item first.
var nameToSearch = "MyName";
var itemIndex = -1;
for(var i = 0; i < JSONparsed.member.length; i++) {
if(JSONparsed.member[i].Full_Name === nameToSearch) {
itemIndex = i;
}
}
And then you can delete the item like you did.
if (itemIndex != -1) {
JSONparsed.member.splice(itemIndex,1);
}
The problem you most likely had was that the itemIndex was allways -1 as indexOf did not know which attribute to check and just checks for the whole object.
Also the following lines have to be after the code above. (So after any changes you make to the json)
// Beautify the resulting JSON file
var JSONformated = JSON.stringify(JSONparsed, null, 4);
I also recomend reading this turtorial about javascript debugging. It makes your live a lot easyier to find mistakes.

Removing root node in json

I have a json data stored in a variable.
var jsonstring;
Json Data:
{ "XYZ": { "abc":[{....}] } }
From above JSON Data, I should not have XYZ node. I need JSON Data as
{ "abc":[{....}] }
How can i remove using Javascript.
If jsonstring is the JSON object, update it
jsonstring = jsonstring["XYZ"]
If jsonstring is a string, do like this.
var json = JSON.parse(jsonstring);
json = json["XYZ"];
If you know the property name you want to remove it's as easy as
json = json.XYZ;
if you don't know it and always want to remove the root note, use
json = json[Object.keys(json)[0]];

Use python to add to javascript array in javascript file

I have this array stored in versions.js
var cc_versions = [
"2016-01-22",
"2016-01-21",
];
var cs_versions = [
"2016-01-23",
"2016-01-21",
];
I have been trying to figure out a way to write new data to the top of the array inside the javascript file with python. I run a python script on my computer almost every day and I want to update this array when I run it so that I can have a website load the versions. Is it possible to do this? I know I could write to the file, but it would just go to the bottom of the file outside of the array. Also there will be multiple arrays, so I'm trying to find some python script that can interact with a javascript file so I can target specific arrays.
You could also try using Genshi template language. One of the tags there is
<?python ... ?>
for example:
<?python
import json
dateInit = []
selectInit = []
for fi in form_items:
if (fi["type"] == "date"):
dateInit.append(fi["id"])
if "attrs" in fi and "format-select" in fi["attrs"]:
selectInit.append(fi["id"])
if not "attrs" in fi:
fi["attrs"] = {}
jsonDateInit = json.dumps(dateInit)
jsonSelectInit = json.dumps(selectInit)
?>
Your response should contain form_items dictionary processed somewhere on the back-end. Then in javascript you can 'accept' the variables using '$'-sign:
var dateitems = JSON.stringify($jsonDateInit);
var select_items = JSON.stringify($jsonSelectInit);
import json
NEW_VARIABLES = [1, 2, 3]
with open('your/json/file.json') as data_file:
json_data = json.load(data_file)
# insert at the beginning of the list
json_data['cc_version'].insert(0, 'something new')
json_data['cs_version'] = NEW_VARIABLES + json_data['cs_version']
# write to json file after modifying data
with open('your/json/file.json', 'w') as output_file:
json.dump(json_data, output_file)
I ended up using json as suggested in the comments
import json
with open("cc_versions.txt") as data:
json = json.load(data)
dates = json["dates"]
dates.append("2016-01-21")
dates = set(dates)
dates = sorted(dates, key=lambda d: map(int, d.split('-')))
dates = dates[::-1]
import json
with open("cc_versions.txt", "w") as outfile:
json.dump({'dates':dates}, outfile, indent=4)

adding variable values in json file using push function

I have a json file and two variables, i want to store the variables values in the json file using push function in json. my code is
var x=xmen;
var z=xmen website
var jsonObj = {
"items":
[
{
"title":"some title",
"url":"some url"
}
]
};
I want my resulting json file to be
var jsonObj = {
"items":
[
{
"title":"some title",
"url":"some url"
}
{
"title":"xmen",
"url":"xmen website"
}
]
};
I dont want to use arrays just while pushing the value using
jsonObj.items.push
i want to call the variable and assign like example
jsonObj.items.push({"title":+x+,"url":+url+}); //just to explain, its not the original function.
I don't think push is your problem. It's your object syntax that's messed up.
Instead of
{"title":+x+,"url":+url+}
Try this instead:
// Assuming that "x" and "url" are valid variables
{"title":x,"url":url}
Here's a quick demo of everything working: http://jsbin.com/zicofoye/1/edit
jsonObj.items.push({
"title":"avengers",
"url":"avengers website"
});

How to extract data from this JSON string?

I'm new to JSON and Jquery, and I can't find how to extract the values of ProjectCode from this JSON string.
[
{
"ProjectID": 3,
"CLustomerCode": "XYZ001",
"ProjectCode": "YZPROJ1",
"Description": "Project1",
"IssueManager": "iant",
"NotificationToggle": false,
"ProjectStatus": null,
"Added": "/Date(1400701295853}/",
"Added By": "iant",
"Changed": "/Date(1400701295853)/",
"Changed By": "iant"
},
{
"ProjectID": 4,
"CustomerCode": "XYZ001",
"ProjectCode": "XYXPROJ2",
"Description": "Projecton:Project2",
"IssweManager": "iant",
"NotificationToggle": false,
"Projectstatus": null,
"Added": "lDate(1400701317980)/",
"AddedBy": "iant",
"Changed": "/Date(1400701317980)/",
"Changed By": "iant"
}
]
The string above is from a variable called data that is the return value from stringify. I expected to be able to do something like
string proj = data[i].ProjectCode;
but intellisense doesn't include any of the properties.
I know very little about JSON - any help appreciated.
Thanks for reading.
Use parseJSON:
var obj = jQuery.parseJSON("{ 'name': 'Radiator' }");
alert(obj.name);
You need to loop through each object returned in the response and get the ProjectCode property inside each one. Assuming the data variable is your JSON this should work:
$.each(data, function(i, obj) {
console.log(obj.ProjectCode);
});
Use JSON.parse():
var a; // Your JSON string
var b = JSON.parse(a); //Your new JSON object
//You can access Project code, use index i in b[i].ProjectCode in a loop
var projectCode = b[0].ProjectCode;
You should post the raw code so its easier to visualize this stuff. Since what you are looking for is the list of ProjectCodes (in this case - ["XYZPROJ1", "XYZPROJ2"]).
It seems like what we have is an array or list ([...]) of projects. Where each project has a ProjectID, CustomerCode, ProjectCode, Description and so on...
So lets assume data points at this JSON blob. Here is how you would go about accessing the ProjectCode:
// Access the "i"th project code
var p_i_code = data[i].ProjectCode;
// How many projects?
var num_projects = data.length; // since data is a list of projects
// Want the list of project codes back? (I use underscore.js)
var project_codes = _.map(data, function(project) {
return project.ProjectCode;
});

Categories

Resources