Google script null object - don't understand why - json

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.

Related

Read local JSON files when dynamically creating functional tests in Intern

I am creating functional tests dynamically using Intern v4 and dojo 1.7. To accomplish this I am assigning registerSuite to a variable and attaching each test to the Tests property in registerSuite:
var registerSuite = intern.getInterface('object').registerSuite;
var assert = intern.getPlugin('chai').assert;
// ...........a bunch more code .........
registerSuite.tests['test_name'] = function() {
// READ JSON FILE HERE
var JSON = 'filename.json';
// ....... a bunch more code ........
}
That part is working great. The challenge I am having is that I need to read information from a different JSON file for each test I am dynamically creating. I cannot seem to find a way to read a JSON file while the dojo javascript is running (I want to call it in the registerSuite.tests function where it says // READ JSON FILE HERE). I have tried dojo's xhr.get, node's fs, intern's this.remote.get, nothing seems to work.
I can get a static JSON file with define(['dojo/text!./generated_tests.json']) but this does not help me because there are an unknown number of JSON files with unknown filenames, so I don't have the information I would need to call them in the declare block.
Please let me know if my description is unclear. Any help would be greatly appreciated!
Since you're creating functional tests, they'll always run in Node, so you have access to the Node environment. That means you could do something like:
var registerSuite = intern.getPlugin('interface.object').registerSuite;
var assert = intern.getPlugin('chai').assert;
var tests = {};
tests['test_name'] = function () {
var JSON = require('filename.json');
// or require.nodeRequire('filename.json')
// or JSON.parse(require('fs').readFileSync('filename.json', {
// encoding: 'utf8'
// }))
}
registerSuite('my suite', tests);
Another thing to keep in mind is assigning values to registerSuite.tests won't (or shouldn't) actually do anything. You'll need to call registerSuite, passing it your suite name and tests object, to actually register tests.

What can JSON strings be used for?

To my understanding, JSON strings were ways to package information to be sent around, much like xml.
This is also what's highly circulated in the stack-exchange questions
eg: What is JSON and why would I use it?
However, a recent bot for a game that I play took json files as "scripts" of actions to perform. In this way, users of the bot were able to customize actions that the bot was expected to perform.
This seemed to violate my mental model of what json's were and what they could accomplish. My current suspicion is that rather than using these "script" json files as packages of information to send, they are instead processed internally by the bot, which then translates our "scripts" into real actions.
Please enlighten me if I've misunderstood what json is.
JSON is just a structure, literally it is "JavaScript Object Notation", http://json.org/.
processed internally by the bot
is basically what is going on.
The json string is parsed into an object, and based on the values of that object the bot reacts. There is no scripting involved in it. However, it is possible that some of the values are literally script in a string, which can be used in JavaScript with eval in order to execute.
I suspect that eval is not being used in that fashion though, and that the bot is simply reading key value pairs to take as instruction for example moveright:5 feet.
Here is a very quick example of taking expected commands in json and then executing them in some sort of process. The implementation is basic, just a proof of concept.
var json = '{ "actions": [ { "speak": "hello world" }, { "color" : "red" } ]}';
var obj = JSON.parse(json);
var i = 0;
var bot = document.querySelector("#bot");
var actions = {
speak : function(text){ bot.innerText = text; },
color : function(c){ bot.style.color = c; }
};
function act(action){
for(var key in action){
var value = action[key];
actions[key](value);
}
if(i <= obj.actions.length)
setTimeout(function(){
act(obj.actions[i++]);
},500);
}
setTimeout(function(){
act(obj.actions[i++]);
},500);
<div id="bot">:)</div>

JSON.parse returning undefined object

Blizzard just shut down their old API, and made a change so you need an apikey. I changed the URL to the new api, and added the API key. I know that the URL is valid.
var toonJSON = UrlFetchApp.fetch("eu.api.battle.net/wow/character/"+toonRealm+"/"+toonName+"?fields=items,statistics,progression,talents,audit&apikey="+apiKey, {muteHttpExceptions: true})
var toon = JSON.parse(toonJSON.getContentText())
JSON.pase returns just an empty object
return toon.toSorce() // retuned ({})
I used alot of time to see if i could find the problem. have come up empty. Think it has something to do with the "responce headers".
Responce headers: http://pastebin.com/t30giRK1 (i got them from dev.battle.net (blizzards api site)
JSON: http://pastebin.com/CPam4syG
I think it is the code you're using.
I was able to Parse it by opening the raw url of your pastebin JSON http://pastebin.com/raw/CPam4syG
And using the following code
var text = document.getElementsByTagName('pre')[0].innerHTML;
var parse = JSON.parse(text);
So to conclude I think it is the UrlFetchApp.fetch that's returning {}
So i found the problems:
I needed https:// in the URL since i found after some hours that i had an SSL error
If you just use toString instead of getContentText it works. Thow why getContentText do not work, i am not sure of.
was same problem, this works for me (dont forget to paste your key)
var toonJSON = UrlFetchApp.fetch("https://eu.api.battle.net/wow/character/"+toonRealm+"/"+toonName+"?fields=items%2Cstatistics%2Cprogression%2Caudit&locale=en_GB&apikey= ... ")

$resource : $save does not work

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.

how to send the data in Json structure

I have a rest service for which I am sending the Json data as ["1","2","3"](list of strings) which is working fine in firefox rest client plugin, but while sending the data in application the structure is {"0":"1","1":"2","2":"3"} format, and I am not able to pass the data, how to convert the {"0":"1","1":"2","2":"3"} to ["1","2","3"] so that I can send the data through application, any help would be greatly appreciated.
If the format of the json is { "index" : "value" }, is what I'm seeing in {"0":"1","1":"2","2":"3"}, then we can take advantage of that information and you can do this:
var myObj = {"0":"1","1":"2","2":"3"};
var convertToList = function(object) {
var i = 0;
var list = [];
while(object.hasOwnProperty(i)) { // check if value exists for index i
list.push(object[i]); // add value into list
i++; // increment index
}
return list;
};
var result = convertToList(myObj); // result: ["1", "2", "3"]
See fiddle: http://jsfiddle.net/amyamy86/NzudC/
Use a fake index to "iterate" through the list. Keep in mind that this won't work if there is a break in the indices, can't be this: {"0":"1","2":"3"}
You need to parse out the json back into a javascript object. There are parsing tools in the later iterations of dojo as one of the other contributors already pointed out, however most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is:
var str = your_incoming_json_string,
// here is the line ...
obj = JSON.parse(string);
// DEBUG: pump it out to console to see what it looks like
a.forEach(function(entry) {
console.log(entry);
});
For the browsers that don't support JSON.parse() you can implement it using json2.js, but since you are actually using dojo, then dojo.fromJson() is your way to go. Dojo takes care of browser independence for you.
var str = your_incoming_json_string,
// here is the line ...
obj = dojo.fromJson(str);
// DEBUG: pump it out to console to see what it looks like
a.forEach(function(entry) {
console.log(entry);
});
If you're using an AMD version of Dojo then you will need to go back to the Dojo documentation and look at dojo/_base/json examples on the dojo.fromJson page.