JSON.parse returning undefined object - json

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= ... ")

Related

Getting JSON from HTTP Discord.Js

Im making a discord bot, and I have a URL here which has some raw json: link here and I want one of the values (hashrateString) to be put inside a embed like:
hashrateString: 1GH
is there a way to do that and if so how?
I never tried this with an external link but it should work the same way.
FIRST: write somewhere high up in your code this line
var fs = require('fs');
var data = JSON.parse(fs.readFileSync('http://ric.pikapools.com/api/stats', 'utf8'));
After you can basically do whatever you want with your new object. There was no hashrateString: 1GH, but hashrateString: 4.68 GH should be accessible with data.algos.primesr.hashrateString (Output: 4.68 GH)
If it, for some weird reason, doesn't accept an URL, just try to copy&paste the text in a json file if possible, and use the path to it
I was able to get this to work by specifying a constant to be the JSON from the url using node-fetch
const ricp = await fetch('http://ric.pikapools.com/api/stats').then(response => response.json());
and find an object in the JSON using
message.channel.send(ricp.algos.primesr.hashrateString)

NativeScript Throwing Error Response with status: 200 for URL: null

I am using Angular4 with TypeScript version 2.2.2
My web app is running fine when I call JSON with Filters but my NativeScript app fails when I call the Filter Values as an Object but works fine when I call filter values as a string.
Error Response with status: 200 for URL: null
THIS WORKS
https://domainname.com/api/v1/searchevents?token=057001a78b8a7e5f38aaf8a682c05c414de4eb20&filter=text&search=upcoming
If the filter value and search value is STRING it works whereas if they are objects as below, it does not work
THIS DOES NOT WORK
https://api.domainname.com/api/v1/searchevents?token=057001a78b8a7e5f38aaf8a682c05c414de4eb20&filter={"limit":"12","skip":"0"}&search={"search":"","latitude":"","longitude":"","categories":"","address":"","type":"upcoming"}
The Code I used is below
getData(serverUrl, type, skip_limit) {
console.log(serverUrl);
let headers = this.createRequestHeader();
let token_value = localStorage.getItem('access_token')
let url;
var filter;
filter = '{"limit":"10","skip":"0"}'
url = this.apiUrl + serverUrl + '?token=' + token_value + '&filter=' + filter
return this.http.get(url, { headers: headers })
.map(res => res.json());
}
The URL as formed above for the API is fine and works fine. Yet the error comes Error Response with status: 200 for URL: null
CAN ANYONE HELP ME SOLVE THIS?
Looks like the issue is the "filter" values are of different type and from what you mentioned as what worked, your service is expecting a string and not an object/array. So it fails to send the proper response when it gets one. With an object in the URL, you may have to rewrite the service to read it as an object (parse the two attributes and get them individually)
To make it simple, you can make these two as two different variables in the URL. like below,
https://api.domainName.in/api/v1/oauth/token?limit=10&skip=0
Be more precise in whats happening in your question,
1) Log the exact URL and post it in the question. No one can guess what goes in "text" in your first URL.
2) Your URL which you mentioned as worked have "token" as part of path, but in the code, its a variable which will have a dynamic value from "token_value".
3) Post your service code. Especially the signature and input parsing part.
Got the solution:
All you have to do is encode the Filter and Search Parameters if it is an Object or Array using Typescript encodeURI()
var filter = '{"limit":"12","skip":"0"}'
var search = '{"search":"","latitude":"","longitude":"","categories":"","address":"","type":"upcoming"}'
var encoded_filter = encodeURI(filter);
var encoded_search = encodeURI(search);
url = this.apiUrl+serverUrl+'?token='+token_value+'&filter='+encoded_filter+'&search='+encoded_search

Google script null object - don't understand why

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.

Polymer core-ajax won't post JSON?

I'm using core-ajax to retrieve JSON data just fine. Turning the component around to post back to the server as JSON is another thing altogether. In all cases, and irrespective of the contentType or handleAs parameters passed in, it appears that my JSON object I'm passing in as an input is being converted back to key=value in the server headers.
The code:
var ajax = document.querySelector('core-ajax');
ajax.method = 'POST';
ajax.handleAs = 'JSON';
ajax.contentType = 'application/json';
ajax.params = JSON.stringify(data);
ajax.go();
Really straightforward. The logs in Go give me:
2014/07/22 14:23:09 utils.go:139: OPTIONS /1/users/173?access_token=(token)
2014/07/22 14:23:09 utils.go:124: POST /1/users/173?access_token=(token)
2014/07/22 14:23:09 users.go:379: full_name=Greg%20Johnson
We've verified that there's no transformation happening on our side. Request headers are going out just fine.
I could completely be missing something. How else can we successfully POST out JSON data?
.params is for URL params. What you want is to post the JSON as the request body? For that, I believe you need to set the .body property:
This should do the trick:
ajax.body = data
See https://github.com/Polymer/core-ajax/blob/master/core-ajax.html#L151

How to POST JSON using Adobe Flex

I'm trying to POST some JSON data using Adobe Flex but having some problems. I'm now getting the error message "A URL must be specified with useProxy set to false", even though I do have useProxy set to false.
Update : code below is now working.
var data:Object = new Object();
data.ipaddr = ipaddr.text;
data.netmask = netmask.text;
data.gatewayip = gatewayip.text;
var jsonData:String = JSON.stringify(data);
var s:mx.rpc.http.HTTPService = new mx.rpc.http.HTTPService();
// URL needs to be specified on a separate line, call is unreliable otherwise
s.url = Utils.getBaseURL() + '/cgi-bin/setnetworksettings';
s.contentType = "application/json";
s.resultFormat = mx.rpc.http.HTTPService.RESULT_FORMAT_TEXT;
s.method = "POST";
s.useProxy = false;
s.addEventListener("result", httpResult);
s.addEventListener("fault", httpFault);
s.send(jsonData);
What do you mean by "doesn't seem to do anything"? No response from the server? Fault instead of result? Which one? Help us help you with more details, just stating it doesn't work is not enough.
First of all, be sure that your URL is correct, you should get something in the service result handler OR fault handler, anything. That should help you diagnose and fix any URL problems if any.
Then for the JSON part, you object is not a valid JSON (no escaping and : instead of =), try sending this first: {"ipaddr":"10.1.1.1"}.
From here it should be easy: as F4L stated, you can use the JSON class to encode a real object directly to JSON.
Hope that helps