Deleting elements out of a json file without getting "null" - javascript

I have a JSON formatted text file that I'm using as kind of a database.
I read the file, use JSON.parse to turn it into an object, use delete on an element, then I JSON.stringifythe object and write it back to the file.
However the resulting file has "null" in the place where the object used to be, which isn't proper JSON, so my program will crash the next time the file is parsed. I don't like it.
How can I delete elements from my file without getting "null" where the element used to be?
Here's how I do it:
data = fs.readFileSync("./manifest/test.json");
contents=JSON.parse(data);
//some logic
delete contents.customers[i].files[j];
fs.writeFileSync("./manifest/test.json",JSON.stringify(contents,null,4));
And the resulting file before:
{
"customers": [
{
"customer": "test",
"files": [
{
"name": "test.flv",
"location": "cloudfront.url.com/check.flv"
}
]
}
]
}
And after:
{
"customers": [
{
"customer": "test",
"files": [
null
]
}
]
}

contacts.customers[i].files.splice(j, 1);
The result is still valid JSON though. JSON.parse should succeed. The error may lie elsewhere.

Related

Customize VSCode new lines on save format

I'm using vscode format on save feature and it was working great. but now it is forcing to insert a line break when using Square Brackets for arrays [ ] on objects. Like:
If I try to write this:
{
"response": {
"status": 200,
"property": ["response"]
}
}
When I hit Ctrl+S to save, it formats the code to:
{
"response": {
"status": 200,
"property": [
"response"
]
}
}
And I don't want that for [ ]
I disabled every setting available relate to add NewLine for both javascript. and typescript.. Any idea how to specify this?

Unable to retrieve contents of JSON post

I have a script in Sheets that is supposed to flatten a JSON post but am having some difficulty getting around the format of the incoming JSON.
Below, I have an example POST which I am trying to parse. Underneath that is my doPost function, with some of the ways I have tried getting the content. doPost uses another function to actually parse the content, but I can't seem to get around what looks like an array formatted JSON?
Here is an example of the POST object:
[
{
"id": "xyz123",
"payload": {
"reference_id": "id_6",
"unit_id": "000111222",
"origin": {
"name": "T-shirt Supply",
"city": "Jiujiang",
"state": "Jiangxi",
"country": "China",
},
"destination": {
"name": "Main Office",
"city": "Surabaya",
"state": "East Java",
"country": "Indonesia",
},
},
"status": "data_received",
"created_at": "2020-01-29T07:41:33.918Z",
"updated_at": "2020-01-29T07:41:33.918Z"
}
]
I have tried in several ways to access the contents, such as payload.reference_id, but for some reason can't find my way into the curled brackets of the JSON object. Here are some of the ways I have tried:
function doPost(e){
var data = e.postData.contents;
// returns JSON formatted [{ "id": "xyz", "payload" : {"reference" : "1", "updated" : true}}]
var data2 = JSON.parse(e.postData.contents);
// returns [object Object]
var data3 = data[0];
// returns [
var data4 = ContentService.createTextOutput(e.postData.contents).setMimeType(ContentService.MimeType.JSON);
// same result as 'data'
return dataX;
}
I have also attempted various workarounds, such as parsing twice, stringify, and more. Any help is greatly appreciated!!!
I think you don't need to parse e.postData.contents, probably it is already an object, not string.
Or if it is string and there is only one element, you can try this:
var data2 = JSON.parse(e.postData.contents.slice(1,-1));
I believe your goal is as follows.
You want to output the object of the 1st element in an array which is your sample value from doPost.
If my understanding is correct, how about the following modification?
Modified script:
function doPost(e){
var data2 = JSON.parse(e.postData.contents);
return ContentService.createTextOutput(JSON.stringify(data2[0])).setMimeType(ContentService.MimeType.JSON);
}
In this modification, it supposes that e.postData.contents is your sample value. Please be careful about this.
When the above-modified script is used, the 1st element of the array is returned.
Note:
When you modified the Google Apps Script, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.
You can see the detail of this in the report of "Redeploying Web Apps without Changing URL of Web Apps for new IDE".
Reference:
createTextOutput()

How to just replace my one property of json object in json array which have large no of json objects in nodejs?

I have searched my many online articles of parsing json array or there exists any npm package to do it.But my all efforts gone in vain.
I have an json array like this =>
{
"pctProjects": [
{
"ID": "1",
"Name": "Software Upgrade",
"Desc": "GO! V1 Chapter 5- EOC Mastery Exercise",
"AppId": "1",
"UserId": "1",
"CreatedDate": "2008-07-30T00:00:00",
"Score": "100",
"SeriesID": "2",
"IsPublished": "1",
"PublishedLMSVariationID": "5",
"IsPCTActive": "0",
"IVTEnabled": "0",
"IsActiveInSelectPopup": "1",
"Chapter": "CH05"
},
{
"ID": "2",
"Name": "Business Venture",
"Desc": "Exploring Volume 1 Chapter 3- TST Exercise",
"AppId": "1",
"UserId": "1",
"CreatedDate": "2008-07-30T00:00:00",
"Score": "100",
"SeriesID": "1",
"IsPublished": "1",
"PublishedLMSVariationID": "7",
"IsPCTActive": "0",
"IVTEnabled": "0",
"IsActiveInSelectPopup": "1",
"Chapter": "CH03"
}
.
.
.
I looped through my json array "pctProjects" using Json.parse method and able to find the object using the property PublishedLMSVariationID which i need to replace with another value, i'm using filesystem module functions like appendFileSync() and writeFileSync() to update the file.But using this methods i have to rewrite other objects data also which i'm not changing and this is not optimised method to do this as i can have n no of objects in that array.
And Using replace-in-file also not helping me to achieve my goal.
Also adding my code snippet what i'm doing right now which is not optimised.
for(let item of gulpJson.pctProjects){
// console.log(typeof touseVariationId)
if(counter==1 && item.PublishedLMSVariationID == results[0]){
item.PublishedLMSVariationID = results[1]
fs.writeFileSync(path.join(dir,'PCT5_MasterPCTProjectsForGulp.json'), JSON.stringify(item,null,4));
counter++;
}
else if(counter==1 && item.PublishedLMSVariationID != results[0]){
fs.writeFileSync(path.join(dir,'PCT5_MasterPCTProjectsForGulp.json'), JSON.stringify(item,null,4));
counter++;
}
else if(item.PublishedLMSVariationID == results[0]){
item.PublishedLMSVariationID = results[1]
fs.appendFileSync(path.join(dir,'PCT5_MasterPCTProjectsForGulp.json'), JSON.stringify(item,null, 4));
// break
// fs.writeFileSync(path.join(dir,'PCT5_MasterPCTProjectsForGulp.json',null, 2), JSON.stringify(item));
}
else
fs.appendFileSync(path.join(dir,'PCT5_MasterPCTProjectsForGulp.json'),","+"\n"+"\t"+ JSON.stringify(item,null, 4));
}
Questions:
Is there any way to just replace my one json property in json array in nodejs???
Much Obliged:).Thanks in advance.
Please comment if any more information is needed.
From what I understand, you are asking if You can edit your JSON file on the file system differentially without rewriting the whole thing. Although I'm sure that that is possible, I would recommend simply rewriting your entire JSON file each time you want to update it. If the JSON is so huge that this becomes too tedious/time consuming, you may be better off using a DB of some sort (MySQL, Mongo, Firebase etc).
My recommendation would be to do it in the following order:
Retrieve JSON string from file (lets call it source.json)
Parse JSON string to get Object using JSON.parse
Update the object you want to update in the parsed object by looping over it and overwriting values as needed.
Use JSON.stringify to get back a string representation (of the entire object as obtained in step 2) and overwrite your source.json with the new JSON
I am able to achieve my result in an optimised way by using the npm replace-in-file module.
Here, is my code snippet where i have used that module:
replace.sync({
files: path.join(dir,'PCT5_MasterPCTProjectsForGulp1.json'),
from: results[0],
to: results[1]
});

Error saving JSON file

I have following JSON file:
weather = [
{
"city": "Munich",
"temp": {
"temp_val": "30 deg",
"temp_unit": "C"
},
"speed": {
"speed_val": 7.31,
"speed_unit": "m/s"
}
}
]
I am new to working with JSON files. I want to save this JSON file as weather.json.
But it gives following error:
Expected value at 1:0 pointing to the first line of the file.
You can't have weather = in your JSON file. JSON stands for JavaScript Object Notation so anything other than a JavaScript Object won't work. You also can't have functions in there. Take a look at the JSON official website to see what the format accepts
This should be correct:
[
{
"city": "Munich",
"temp": {
"temp_val": "30 deg",
"temp_unit": "C"
},
"speed": {
"speed_val": 7.31,
"speed_unit": "m/s"
}
}
]
You can then add this line in your javascript once you load the file into a string:
weather = JSON.parse(some_string);
You are manipulating this file as if it was going to be rendered as JavaScript. This should only be plain text, no variable definitions. Just plain key value pairs. If you want to assign variable, set it to a .js file and render it in a browser.
You should look at an example file for JSON and model it. Remember that JSON is just plain text organized in a particular way.

result not coming with d3js?

After lot of help from stackoverflow folks,finally resolved my json and now its looking good.
luck.json--->
{
"PERFECT_JSON_object":
{
"51b59c1bbae1c":
[
{ "id": "parties", "float_1": "0.006" , "float_2": "0.9"},
{ "id": "royal-challenge", "float_1": "0.02" , "float_2": "0.333" },
{ "id": "star-speak","float_1": "0.02","float_2":"0.1" }
],
"51b59c1bbae3c":
[
{ "id": "parties","float_1": "0.006" , "float_2": "0.9"},
{ "id": "star-speak","float_1": "0.02", "float_2": "0.009" }
],
"51b59c1bbae5c":
[
{ "id": "parties","float_1": "0.006" , "float_2": "0.9"}
]
}
}
I have been trying to get my head around d3js with json,and I must say I have progressed quite a bit.But I am still not able to get the output with json data.
I went through these link`s but dint help.
https://github.com/mbostock/d3/wiki/Requests
d3.js & json - simple sample code?
Access / process (nested) objects, arrays or JSON
MyFIDDLE with json(no output,something wrong in here)
same fiddle with some static values( without Json)--
This is the result that I want.
I know that d3.json method requires json file to be on server.For temporary basis,as the json file is small can we include it directly in a variable in our d3 script??
I think I am messing up with json data in a wrong way.Can somebody help me with it
Yes, you can just add the JSON in a variable and run it this way. See here for the updated jsfiddle. You basically just add your JSON after var data =.

Categories

Resources