Unable to retrieve contents of JSON post - javascript

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()

Related

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]
});

Can't correctly print data from JSON array using jQuery

I've got this simple array of data in a json file but trying to extract the data is proving hard for a novice like me. Here is the array that I have been given.
var clients = [
{
"clientid": "456489",
"client-name": "John Smith",
"email": "a.smith#gmail.com"
},
{
"clientid": "654987",
"client-name": "Mark Barnes",
"email": "barnesdog#gmail.com"
},
{
"clientid": "987981",
"client-name": "Taylor Johnson",
"email": "taylor.j#gmail.com"
},
]
My first test was this to see if I could get a success message or not. It has not worked and i'm just not sure why.
$(document).ready(function() {
$.getJSON("clients.json", function(data){
$.each(data, function (index, value) {
console.log(data);
});
});
});
I know this is simple, but I have never done this before, thanks in advance.
Are you using Chrome and opening the HTML file that contains the code from file? By default Chrome does not allow this. Try it in Firefox, if that works that was the issue. This will not happen if your HTML file is on a server in the web.
removing the trailing , from the list of objects in json and var clients = from the top and it should work.

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.

How Do I See the Output of Changes to JSON

Updated to try to be more clear given the comments (Thank you for comments)
I apologize in advance for this question. I may just not have the vocabulary to properly research it. If I have an array of objects called restaurants stored in my project, for example:
restaurants: [
{
"name": "joes's pizza",
"url": "joespizza.com",
"social properties": {
"Facebook":"fb.com/pizza",
"Instagram":"instagram.com/pizza",
"googlePlus":"pizza+",
"Twitter":"twitter.com/pizza"
}
},
{
"name": "tony's subs",
"url": "tonys.com",
"social properties": {
"Facebook":"fb.com/subs",
"Instagram":"instagram.com/subs",
"googlePlus":"subs+",
"Twitter":"twitter.com/subs"
}
},
{....}
]
I then run a function to add a unique idea to all the objects in the array. The result of console.log(restaurants) is this:
{
"id": 3472,
"name": "joes's pizza",
"url": "joespizza.com",
"social properties": {
"Facebook":"fb.com/pizza",
"Instagram":"instagram.com/pizza",
"googlePlus":"pizza+",
"Twitter":"twitter.com/pizza"
}
},
{
"id": 9987,
"name": "tony's subs",
"url": "tonys.com",
"social properties": {
"Facebook":"fb.com/subs",
"Instagram":"instagram.com/subs",
"googlePlus":"subs+",
"Twitter":"twitter.com/subs"
}
},
{....}
]
I would now like to have this updated array of objects available to look at in my project, via the text editor, as a variable or restaurants.json file. How do I actually see the new modified json array and how do i save it so that i can work with it the same way i did this one above? I am currently doing this in the browser. I can see the results if i log it to the console but I need to be able to work with the new output. Thanks for taking the time to answer.
You can encode/decode JSON with JSON.stringify() and JSON.parse().
Aside from converting to/from JSON, you work with standard JS objects and arrays:
var array = JSON.parse(json_str);
array[0].address = "5th Avenue";
console.log(JSON.stringify(array));
Well, there's really not enough information in your question but I assume a few things:
You've loaded the json data from somewhere and it has been turned into a javascript object.
You've edited the object somehow and wish to convert it back to json and save the changes.
Assuming the above to be true, you just need to serialize the object back to json and submit it back to your server where you can save it in any manner you deem appropriate.
You can serialize the javascript object with JSON.stringify() (see https://stackoverflow.com/a/912247/4424504)
Add the serialized json to a hidden field on the form and submit it.
On the server when processing the form submission, grab the data from the hidden field and do with it what you wish.
Or get it back to the server any way you wish (ajax call, whatever) the key point is to serialize the object to a json string and save it
Hope that helps...

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