I am trying to import data from a JSON POST API into a Google Sheet. I have been able to log the full JSON response but now can't filter it to just the attribute that I require as I keep getting an error saying that the attribute is 'undefined' when I try to log DIV1. I have tried testing it for other parameters such as the DrawDate and DrawType, but keep getting the same message.
function main() {
// Make a POST request with a JSON payload.
var data = {
'CompanyId': 'GoldenCasket',
'MaxDrawCount': 1,
'OptionalProductFilter':['OzLotto']};
var options = {
'method' : 'post',
'contentType': 'application/json',
// Convert the JavaScript object to a JSON string.
'payload' : JSON.stringify(data)};
var response = UrlFetchApp.fetch('https://data.api.thelott.com/sales/vmax/web/data/lotto/opendraws', options);
Logger.log('output: '+ response);
var json = JSON.parse(response)
var DIV1 = json["Div1Amount"];
Logger.log(DIV1)
}
I am getting this response to the request, but I would like to receive just the Div1Amount.
output:
{
"Draws":[
{
"ProductId":"OzLotto",
"DrawNumber":1323,
"DrawDisplayName":"Oz Lotto $80,000,000",
"DrawDate":"2019-06-25T00:00:00",
"DrawLogoUrl":"http://media.tatts.com/TattsServices/Lotto/Products/OzLotto_v1.png",
"DrawType":"Jackpot",
"Div1Amount":80000000.0000,
"IsDiv1Estimated":false,
"IsDiv1Unknown":false,
"DrawCloseDateTimeUTC":"2019-06-25T09:35:00",
"DrawEndSellDateTimeUTC":"2019-06-25T09:30:00",
"DrawCountDownTimerSeconds":538150.0
}
],
"ErrorInfo":null,
"Success":true
}
In your response, Div1Amount is inisde Draws list. So, to do that, you have to get the list and iterate through the list then var DIV1 = listObj["Div1Amount"]; will work. Sample code:
//after `var json = JSON.parse(response)` line, change your code with this:
var drawList=json ["Draws"];
//now iterate the list:
for(var i=0;i<drawList.length;i++)
{
var DIV1=drawList[i]["Div1Amount"];
console.log(DIV1);
}
Related
I want to add a JSON element to a JSON file using the data given by a POST request. This already kind of works, I just can't figure out how to add the id to the data, how do I do that?
I tried a lot, I have created a completely new JSON object and tried to add it to my file which didn't work and I tried adding data to the data given from the POST request like this: body += { "id": 10 }; which produces an undefined error.
Here is how I handle the POST request:
} else if (req.method === 'POST' && pathname === 'Kunden') {
res.writeHead(200, {
'Content-Type' : 'application/json'
});
var body = '';
req.on('data', function(data) {
body += data;
});
req.on('end', function() {
fs.readFile('Kunden.json', function(err, kundenJSON) {
if (err) {
console.log(err);
}
var kunden = JSON.parse([kundenJSON]);
kunden.kunde.push(JSON.parse(body));
kundenJSON = JSON.stringify(kunden);
fs.writeFile('Kunden.json', kundenJSON, function(err) {
if(err) {console.log(err);
}});
});
});
}
}).listen(8081);
and here is my already existing JSON file:
{"kunde":[{"id":1,"name":"Customer1"},{"id":2,"name":"Customer2"},{"id":3,"name":"Customer3"}]}
Basically I get the "name" from the POST req and I have to add the following id (in the first request this would be 4, then 5 and so on) to it and then append it to my file.
In the end my file should look like this:
{"kunde":[{"id":1,"name":"Customer1"},{"id":2,"name":"Customer2"},{"id":3,"name":"Customer3"},{"id":4,"name":PostData"}]}
But I can only manage this right now:
{"kunde":[{"id":1,"name":"Customer1"},{"id":2,"name":"Customer2"},{"id":3,"name":"Customer3"},{"name":PostData"}]}
If I understand you correctly, you want to add and id to the new object when you save it to the file. This is basically easy, but you should also know how to keep track of the ids properly.
var kunden = JSON.parse([kundenJSON]);
var newKunde = JSON.parse(body);
newKunde.id = 4;
kunden.kunde.push(newKunde);
kundenJSON = JSON.stringify(kunden);
The problems I'm talking about is, how to you get to know the new id? You could just say newId = kunden.kunde.length + 1 - but if you delete one later on, you will have duplicate ids. You also need to think about how to handle unique ids for the future.
I have pass a collection of objects through http post in angular js.
The code is as follows:
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data.ContentId, { Selected: true }); // I could able to get all the selected objects here, No problem with it
var jsonData = angular.toJson(contents); //It is not able to convert to Json if there are more than 5 records
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent?jsonData=' + jsonData, {});
promise.success(function () {
window.location.reload();
});
[ReferrerFilterAttribute]
[HttpPost]
[System.Web.Http.ActionName("CmsPublishApprovedContent")]
public void CmsPublishApprovedContent(string jsonData)
{
var contents = JsonConvert.DeserializeObject<List<ContentNodeInWorkFlow>>(jsonData);
foreach (var content in contents)
{
_contentService.PublishContent(content.ContentId, userId);
}
}
}
The above code works fine if there are 5 records or less. If there are more records, I could able to get all the selected record
objects in the variable 'contents'. But the problem is occuring when converting to Json for all those objects. I
have about 500 records to pass through. How can do I it?
There is no specific reason to convert to JSON data. I just need to extract the ids of all the selected items. I have modified the above code as below:
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data, { Selected: true });
var abc = [];
angular.forEach(contents, function(content)
{
abc.push(content.ContentId); // got all the ids in the array now
});
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,{contents : abc});
promise.success(function () {
window.location.reload();
});
}
I have just took an array and pushed all the content ids into it. I could able to see all the ids in the array now. I tried to pass the array as above.
How to retrieve those array in the code behind.
[ReferrerFilterAttribute]
[HttpPost]
[System.Web.Http.ActionName("CmsPublishApprovedContent")]
public void CmsPublishApprovedContent(int[] abc)
{}
I do not see any values obtained under int[] abc. What will be the datatype for the parameter in the method call above.
You need second argument of $http.post method. You have to send such data by POST requests, not in query of url. You can put some data into body of the post request.
You need this:
var postBodyWithHugeAmountOFData = {data: [1,2,3,4,5...500]};
$http.post(url, postBodyWithHugeAmountOFData).success(function () {});
Also, you must be ready to handle this request in your backend.
is there any specific reason u want to pass this data as a JSON?.
if u r using Web API in that case u can pass the object as it is but only make sure that collection in web API method contains all the property in javascript collection
Thank you for all your posts. It's working fine without converting to Json. The code is as below.
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data, { Selected: true });
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,contents);
promise.success(function () {
window.location.reload();
});
}
and the signature would be
public void CmsPublishApprovedContent(List<ContentNodeInWorkFlow> abc)
{
}
I need to post some data to server in ajax call. I am binding data into json format and posting it to server:
var BookMarkData = JSON.stringify(postData);
self.app.router.navigate('#hotels/' + BookMarkData, true);
I want to show only 4 elements from postdata JSONArray in the url. But I need to pass entire data to server.
fetchResults: function(PostData) {
var self = this;
var postData = JSON.parse(hashedPostData);
.......
}
How can I pass entire information to fetch results by hiding some information in the url?
If you need to show only 4 elements from postdata I assume that it is an array. Use slice:
var bookMarkData = JSON.stringify(postData),
routeData = JSON.stringify(postData.slice(0, 4))
self.app.router.navigate('#hotels/' + bookMarkData, true);
bookMarkData still holds the the whole array.
Full code:
$.post('test.php', {
id: id
},function (data) {
console.log(data);
var Server = data.response.server;
var Photo = data.response.photo;
console.log(Server);
console.log(Photo);
});
in data i get json:
{
"server":9458,
"photo":
"[{\"photo\":\"0d6a293fad:x\",\"sizes\":
[[\"s\",\"9458927\",\"1cb7\",\"PX_xDNKIyYY\",75,64],
[\"m\",\"9458927\",\"1cb8\",\"GvDZr0Mg5zs\",130,111],
[\"x\",\"9458927\",\"1cb9\",\"sRb1abTcecY\",420,360],
[\"o\",\"9458927\",\"1cba\",\"J0WLr9heJ64\",130,111],
[\"p\",\"9458927\",\"1cbb\",\"yb3kCdI-Mlw\",200,171],
[\"q\",\"9458927\",\"1cbc\",\"XiS0fMy-QqI\",320,274],
[\"r\",\"9458927\",\"1cbd\",\"pU4VFIPRU0k\",420,360]],
\"kid\":\"7bf1820e725a4a9baea4db56472d76b4\"}]",
"hash":"f030356e0d096078dfe11b706289b80a"
}
I would like get parametrs server and photo[photo]
for this i use:
var Server = data.server;
var Photo = data.photo;
console.log(Server);
console.log(Photo);
but in concole i get undefined
Than i use code:
var Server = data.response.server;
var Photo = data.response.photo;
console.log(Server);
console.log(Photo);
But now in console i see:
Uncaught TypeError: Cannot read property 'server' of undefined
Why i get errors and how get parametrs?
P.S.: All code php and jquery find here
Just set proper data type json, the default one is string.
And your data is directly under data variable!
$.post('test.php', {
id: id
},function (data) {
console.log(data);
var Server = data.server;
var Photo = data.photo;
console.log(Server);
console.log(Photo);
}, 'json');
Another solution is setting proper header in you PHP response:
Content-Type text/javascript; charset=UTF-8
then jQuery Intelligent Guess, will set proper data type itself.
You can use parseJSON method, exposed by jQuery. This enables you to map the properties to a type, of sorts, such as:
var results = jQuery.parseJSON(jsonData);
for (int i = 0; i < results.length; i++) {
alert(results[i].name + ":" + results[i].date);
}
You may need to tweak the inputs and exact use of the outputs in accordance with your data and requirements.
getJSON() will parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON).
You can get all the values in an array using a for loop:
$.getJSON("url_with_json_here", function(data){
for (var i=0, len=data.length; i < len; i++) {
console.log(data[i]);
}
});
Another example:
Parse a JSON string.
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" )
;
I am trying to call the server side from JavaScript and then pass a string array back to JavaScript, but running into problems.
// Call the server-side to get the data.
$.ajax({"url" : "MyWebpage.aspx/GetData",
"type" : "post",
"data" : {"IdData" : IdData},
"dataType" : "json",
"success": function (data)
{
// Get the data.
var responseArray = JSON.parse(data.response);
// Extract the header and body components.
var strHeader = responseArray[0];
var strBody = responseArray[1];
// Set the data on the form.
document.getElementById("divHeader").innerHTML = strHeader;
document.getElementById("divBody").innerHTML = strBody;
}
});
On the ASP.Net server side, I have:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object GetTip(String IdTip)
{
int iIdTip = -1;
String[] MyData = new String[2];
// Formulate the respnse.
MyData[0] = "My header";
MyData[1] = "My body";
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(MyData);
return strResponse;
}
I am probably mixing things up, as I am still new to JSON.
UPDATE with error code:
Exception was thrown at line 2, column 10807 in http://localhost:49928/Scripts/js/jquery-1.7.2.min.js
0x800a03f6 - JavaScript runtime error: Invalid character
Stack trace:
parse JSON[jquery-1.7.2.min.js] Line 2
What is my problem?
I modified your ajax call script to :
// Call the server-side to get the data.
$.ajax({
url: "WebForm4.aspx/GetTip",
type: "post",
data: JSON.stringify({ IdTip: "0" }),
dataType: "json",
contentType: 'application/json',
success: function (data) {
// Get the data.
var responseArray = JSON.parse(data.d);
// Extract the header and body components.
var strHeader = responseArray[0];
var strBody = responseArray[1];
// Set the data on the form.
document.getElementById("divHeader").innerHTML = strHeader;
document.getElementById("divBody").innerHTML = strBody;
}
});
Note that I added contentType: 'application/json' and changed
var responseArray = JSON.parse(data.response);
to
var responseArray = JSON.parse(data.d);
This s purely out of guess work. But see if this is what you are getting:-
In your Ajax call, your data type is json and looking at the method you are returning a json string. So you do not need to do JSON.parse(data.response). Instead just see if the below works for you. Also i dont see a response object in your Json, instead it is just an array. So it must be trying to parse undefined
var strHeader = data[0];
var strBody = data[1];