In Google Apps Script, I'm pulling data from an API. In the code below, the "output" variable contains an array of arrays. There is always at least one ["Response"] object, but sometimes there are 2.
My problem is, the code below isn't returning the second object (["Response"][1]) when it is present. I tried removing the "if" statement, but I get an error saying "TypeError: Cannot read property "Product" from undefined".
Does anyone know how to get the second object when it's present and ignore it when it's not?
var data = reportAPI();
var applications = data["applications"];
var output = []
applications.forEach(function(elem,i) {
output.push(["ID",elem["Id"]]);
output.push([elem["Response"][0]["Product"],elem["Response"][0]["Status"]]);
if (["Response"][1] != null) {
output.push([elem["Response"][1]["Product"],elem["Response"][1]["Status"]]);
}
}
P.S. I would even be happy with replacing the undefined object with "", but I'm not sure how to do it.
How about this modification? Please think of this as one of several answers. I used forEach to elem["Response"]. By this, values can be pushed by the number of elem["Response"].
From :
applications.forEach(function(elem,i) {
output.push(["ID",elem["Id"]]);
output.push([elem["Response"][0]["Product"],elem["Response"][0]["Status"]]);
if (["Response"][1] != null) {
output.push([elem["Response"][1]["Product"],elem["Response"][1]["Status"]]);
}
}
To :
applications.forEach(function(elem) {
output.push(["ID",elem["Id"]]);
elem["Response"].forEach(function(elem2) {
output.push([elem2["Product"],elem2["Status"]]);
});
});
If this didn't work, please tell me. I would like to modify.
The example below helps to account for the cases where the Response[0] or Reponse[1] are not "undefined" or "null". Putting !() will turn the Boolean values for "undefined" or "null" to true.
applications.forEach(function(elem,i) {
output.push(["ID",elem.Id]);
if(!(elem.Reponse[0]))
output.push([elem.Response[0].Product,elem.Response[0].Status]);
if (!(elem.Response[1])) {
output.push([elem.Response[1].Product,elem.Response[1]Status]);
}
}
Related
I have a problem with my application. Anyone can help me?
Error:
Converting circular structure to JSON
My Service to create items and save on localstorage:
addItem(item: Item): void {
this.itens.unshift(item);
let itens;
if (localStorage.getItem('itens') == null){
itens = [];
itens.unshift(itens);
localStorage.setItem('itens', JSON.stringify(itens));
} else {
JSON.parse(localStorage.getItem('itens'));
itens.unshift(itens);
localStorage.setItem('itens', JSON.stringify(itens));
}
}
And my component.ts:
addItem(): void {
this.itemAdicionado.emit({
nome: this.nome,
unidade: this.unidade,
quantidade: this.quantidade,
preco: this.preco,
perecivel: true,
validade: this.validade,
fabricacao: this.fabricacao,
});
this.nome = '';
this.unidade ;
this.quantidade ;
this.preco;
this.validade;
this.fabricacao;
console.log(this.nome, this.unidade, this.quantidade, this.preco, this.validade, this.fabricacao);
}
This isn't an Angular error. It's a JavaScript runtime error thrown by the JSON.stringify function. The error tells you that itens contains a circular object reference. This is OK while you run the application, but when stringifying it causes a problem: the JSON generated would become infinitely long.
As Kevin Koelzer indicated in his answer. The problem is that you wrote itens.unshift(itens);. Basically this adds the array of items to the array of items, thus creating a circular reference. Therefore, writing itens.unshift(item); instead solves your problem and is probably what you intended to do anyway.
itens.unshift(itens);
could this be:
itens.unshift(iten);
I'm starting to write Google scripts to automatize certain tasks, and here I'm stuck on a problem I can't figure out by myself. I must say I'm neither an expert in app scripts (yet) nor in javascript.
Here is my problem. I make a call to a (private) REST API to retrieve some data. I get the result, parse it to get a Json object. Then I want to write some properties in a spreadsheet. For some reason, I can't get to manipulate nested objects.
Say I have a list of this json payload :
{
id: 2146904633,
status: "in_progress",
success_probability: 99,
amount: "0.0",
decision_maker: "Bob Mauranne",
business_contact: {
id: 2142664162,
nickname: "NIL",
}
}
EDIT : I made a mistake with the code I pasted (businessContact was not declared, instead a variable bc was declared).Thanks for the comment :) The code below is correct now, but still doesn't work.
I get it like with this (overly simplified) code :
var response = UrlFetchApp.fetch(url);
var dataAll = JSON.parse(response.getContentText());
var data, businessContact;
for (i = 0; i < dataAll.length; i++) {
data = dataAll[i];
businessContact = data.business_contact;
Logger.log(data.status);
Logger.log(businessContact);
Logger.log(businessContact.id);
}
My problem is that when I call businessContact.id I get the error "TypeError: unable to read property id from null object". And I don't understand since I can see the content from businessContact : either from the log call or from the debugger, it's definately not null.
It seems to happen only on nested objects, because on simple properties, I don't have any error. And I have the same problems on all nested objects, whatever json payload I've tried so far...
I searched on the internet for a solution but found none. It probably is very basic, but I can't get it to work.
Any idea ?
You never define "businessContact" that your using in the logger. You define "bc" but not "businessContact". If you changed it to Logger.log(bc.id) it should work.
Here is a trimmed down version of what your trying to do also.
function getJSON() {
var url = "your url";
var response = UrlFetchApp.fetch(url).getContentText();
var data = JSON.parse(response)
data.forEach(function(item) {
Logger.log(item.business_contact.id)
})
}
Heres an example pulling weather data.
function myFunction() {
var url = "https://www.aviationweather.gov/gis/scripts/TafJSON.php";
var response = UrlFetchApp.fetch(url).getContentText();
var data = JSON.parse(response)
data.features.forEach(function(feature) {
Logger.log(feature.properties.id)
})
}
I finally found the solution. This code is in a loop, sometimes the object business_contact is null and I hadn't seen it :|
Clearly I should stop working late in the evening when I learn a new technology ...
My bad, sorry for the noise, and thanks for the answers and comments guys.
Consider a REST URL like /api/users/findByCriteria which receives POSTed JSON that contains details of the criteria, and outputs a list of Users.
How would one call this with Restangular so that its results are similar to Restangulars getList()?
Restangular.all('users').post("findByCriteria", crit)... might work, but I don't know how to have Restangular recognize that the result will be a list of Users
Restangular.all('users').getListFromPOST("findByCriteria", crit)... would be nice to be able to do, but it doesn't exist.
Doing a GET instead of a POST isn't an option, because the criteria is complex.
Well,
I experience same problem and I workaround it with plain function, which return a plain array of objects. but it will remove all Restangular helper functions. So, you cant use it.
Code snippet:
Restangular.one('client').post('list',JSON.stringify({
offset: offset,
length: length
})).then(
function(data) {
$scope.clients = data.plain();
},
function(data) {
//error handling
}
);
You can get a POST to return a properly restangularized collection by setting a custom handler for OnElemRestangularized in a config block. This handler is called after the object has been Restangularized. isCollection is passed in to show if the obect was treated as a collection or single element. In the code below, if the object is an array, but was not treated as collection, it is restangularized again, as a collection. This adds all the restangular handlers to each element in the array.
let onElemR = (changedElem, isCollection, route, Restangular: restangular.IService) => {
if (Array.isArray(changedElem) && !isCollection ) {
return Restangular.restangularizeCollection(null, changedElem, changedElem.route);
}
return changedElem;
};
RestangularProvider.setOnElemRestangularized(onElemR);
I have a json file called data.json containing some data:
[
{
"name" : "toto"
}
]
And the script I wrote to manage it :
var Data = $resource("data.json", {},
{
query: {method:'GET',isArray:true}
});
var data = Data.query(function()
{
var d = data[0];
d.name = "Titi";
d.$save();
});
Everything work before I call $save() on my object. I have this error:
[11:30:24.962] "Error: [$resource:badcfg] Error in resource configuration.
Expected response to contain an object but got an array
I don't really know the problem. I have already read many examples and documentations but this does not seem clearer to me.
Just guessing to help quickly here... You may have several issues, var d = data[0]. data should be from an argument/parameter of the function not the var data which is null until the return result from Data.query changes it. $save should also likely be on the $resource object, not the object in the array. Not an angular person, but guessing that might be the case.
Good evening everyone. I am currently using MVC 3 and I have a viewmodel that contains a property that is a List. I am currently using json2's JSON.stringify method to pass my viewmodel to my action method. While debugging I am noticing that all the simple properties are coming thru but the collection property is empty even though I know for sure that there is at least one object in the collection. I wanted to know if there is anyone that is running into the same issue. Below is the code that I am using to post to the action method:
$.post("/ReservationWizard/AddVehicleToReservation/",
JSON.stringify('#ViewData["modelAsJSON"]'),
function (data) {
if (data != null) {
$("#vehicle-selection-container").html(data);
$(".reservation-wizard-step").fadeIn();
}
});
The object #ViewData["modelAsJSON"] contains the following json and is passed to my action method
{"NumberOfVehicles":1,"VehiclesToService":[{"VehicleMakeId":0,"VehicleModelId":0}]}
As you can see the property "VehiclesToService" has one object but when it gets to my action method it is not translated to the corresponding object in the collection, but rather the collection is empty.
If anyone has any insight into this issue it would be greatly appreciated.
Thanks in advance.
UPDATE
OK after making the recommended changes and making the call to new JavaScriptSerializer().Serialize(#Model) this is the string that ultimately gets sent to my action method through the post
'{"NumberOfVehicles":1,"VehiclesToService":[{"VehicleMakeId":0,"VehicleModelId":0}]}'
I can debug and see the object that gets sent to my action method, but again the collection property is empty and I know that for sure there is at least one object in the collection.
The AddVehicleToReservation action method is declared as follows:
public ActionResult AddVehicleToReservation(VehicleSelection selections)
{
...
return PartialView("viewName", model);
}
Here's the problem:
JSON.stringify('#ViewData["modelAsJSON"]')
JSON.stringify is a client side function and you are passing as argument a list that's stored in the ViewData so I suppose that it ends up calling the .ToString() and you have
JSON.stringify('System.Collections.Generic.List<Foo>')
in your final HTML which obviously doesn't make much sense. Also don't forget that in order to pass parameters to the server using the $.post function the second parameter needs to be a javascript object which is not what JSON.stringify does (it generates a string). So you need to end up with HTML like this:
$.post(
'ReservationWizard/AddVehicleToReservation',
[ { id: 1, title: 'title 1' }, { id: 2, title: 'title 2' } ],
function (data) {
if (data != null) {
$('#vehicle-selection-container').html(data);
$('.reservation-wizard-step').fadeIn();
}
}
);
So to make this work you will first need to serialize this ViewData into JSON. You could use the JavaScriptSerializer class for this:
#{
var myList = new JavaScriptSerializer().Serialize(ViewData["modelAsJSON"]);
}
$.post(
'#Url.Action("AddVehicleToReservation", "ReservationWizard")',
// Don't use JSON.stringify: that makes JSON request and without
// proper content type header your sever won't be able to bind it
#myList,
function (data) {
if (data != null) {
$('#vehicle-selection-container').html(data);
$('.reservation-wizard-step').fadeIn();
}
}
);
And please don't use this ViewData. Make your views strongly typed and use view models.