I am attempting to use cURL with the Pusher API (pusher.com). However I keep getting the response "Invalid JSON provided (could not parse)". Any help would be appreciated, here is my trigger function:
function trigger(name, data, channel)
string_to_sign = "POST\n/apps/"..pusher_app_id.."/events\n"..params
signature = hmac.digest("sha256", string_to_sign, pusher_secret)
md5 = md5.sumhexa('{"name":"foo","channel":"test-channel","data":"{\"some\":\"data\"}"}');
c = curl.new()
c:setopt(curl.OPT_URL, pusher_server..'apps/'..pusher_app_id..'/events'..'?'..params..'&auth_signature='..signature..'&body_md5='..md5)
c:setopt(curl.OPT_POST, true)
c:setopt(curl.OPT_HTTPHEADER, "Content-Type: application/json")
c:setopt(curl.OPT_POSTFIELDS, '{"name":"'..name..'","channel":"'..channel..'","data":"{\"some\":\"data\"}"}')
c:perform()
c:close()
end
If I print the JSON I am putting in OPT_POSTFIELDS and paste it into a json validator, it is indeed completely valid. According to the docs this is the proper usage for /events and my authentication is also working fine.
I had gone back through my function applying the suggestions moteus commented and was able to resolve my problem by fixing the md5 and applying it to the signature. I am also using the luajson module to take care of encoding. This seemed to fix the issue.
function trigger(name, data, channel)
data_table = {
["name"] = name,
["channel"] = channel,
["data"] = data
}
json_data = json.encode(data_table)
md5 = md5.sumhexa(json_data)
string_to_sign = "POST\n/apps/"..pusher_app_id.."/events\n"..params.."&body_md5="..md5
signature = hmac.digest("sha256", string_to_sign, pusher_secret)
c:setopt(curl.OPT_URL, pusher_server..'apps/'..pusher_app_id..'/events'..'?'..params..'&auth_signature='..signature..'&body_md5='..md5)
c:setopt(curl.OPT_POST, true)
c:setopt(curl.OPT_HTTPHEADER, "Content-Type: application/json")
c:setopt(curl.OPT_POSTFIELDS, json_data)
c:perform()
c:close()
end
Related
Following is the code snippet where I am observing error: "malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "(end of string)") at"
Error observed is at the decode_json line. Can someone point out what is the error?
my $serverurl = "http://mycompany.net/rest/api/2/";
my $username = 'my.email#domain.com';
my $password = "mypassword\#2019";
my $i ;
my $test;
my $headers = {Accept => 'application/json', Authorization => 'Basic ' .encode_base64($username . ':' . $password)};
my $client = REST::Client->new();
my $idartinstance;
my $idartinstance1;
if (!$idartinstance)
{
print " Trying to Connect to URL using REST client interface \n\n";
$idartinstance1 = $client->GET($serverurl."serverinfo",$headers);
$idartinstance = decode_json($idartinstance1->responseContent());
}
When I print $idartinstance, I get this:
REST::Client=HASH(0x8682024)->responseContent()
Does this mean, it is not able to find REST client?
[EDIT] I have modified the script as below and no difference in the errors.
my $serverurl = "https://mycompany.net/rest/api/3/";
my $username = 'my.email#domain.com';
my $password = 'pf9fCdkGXmi4pMHiwIh74A0D';
my $headers = {Accept => 'application/json', Authorization => 'Basic ' . encode_base64($username . ':' . $password)};
my $client = REST::Client->new();
if (!$idartinstance)
{
print " Trying to Connect to JIRA using REST client interface \n\n";
$client->GET($serverurl."serverInfo", $headers);
print $client->responseContent();
$idartinstance = decode_json($client->responseContent());
}
Now I have used encoded password. Error is same: malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "(end of string)"). Tried accessing "https://mycompany.net/rest/api/3/serverInfo" via web browser and able to get the details.
Once you get a response, you have to check that its what you want.
if( $client->responseCode() eq '200' ){
print "Success\n";
}
You may also want to check that the content-type is what you expect. If it's supposed to be JSON, check that it is:
if( $client->responseHeader('Content-Type') =~ m|\Aapplication/json\b| ) {
print "Got JSON\n";
}
Once you've established that you have what you wanted, pass the message body off to the JSON decoder.
my $data = decode_json($client->responseContent());
You might also try to catch errors where you should have valid JSON but don't. The block eval can handle that (and see the many sources of the proper employment of eval for its best use):
my $data = eval { decode_json(...) };
I find that I tend to get the wrong content in two situations:
the wrong endpoint, from which a 404 handler returns HTML
a captive portal, which also returns HTML
I think you're misreading the documentation for the module. From the synopsis there, the example that most closely resembles yours is the first one:
my $client = REST::Client->new();
$client->GET('http://example.com/dir/file.xml');
print $client->responseContent();
Notice, in particular, that this example does nothing with the return value from GET(). In your example you do the equivalent of this:
my $client = REST::Client->new();
my $resp = $client->GET('http://example.com/dir/file.xml');
print $resp->responseContent();
As it happens, although there is no documented return value from GET() [Update: I was wrong here - see the first comment - but the return value is really only intended for chaining method calls], it actually returns the object that it was passed, so your approach should work. But it's generally a bad idea to not follow the documentation.
So what is actually going wrong? Well, I'm not sure. As I said, your approach should (accidentally) work. But the error message you're getting tells us that what you're passing to decode_json() is a REST::Client object, not a string containing JSON. I don't think that's how your code should work. Perhaps the code you've shown us isn't actually the code you're running.
The best approach to debug this is to follow the advice from Quentin in the first comment on your question - print the value that you're trying to pass to decode_json() before passing it to the function. In fact, that's good general programming advice - originally write out your code step by step, and only combine steps once you know that the individual steps are working correctly.
Using your variable names, I think your code should look like this:
my $client = REST::Client->new();
# ...other code...
$client->GET($serverurl."serverinfo", $headers);
print $client->responseContent();
# And, only once you've established that
# $client->responseContent() returns what
# you expect, you can add this:
$idartinstance = decode_json($client->responseContent());
If the print() statement doesn't show you JSON, then update your question to add whatever is printed and we'll take a further look.
EDIT: Here's a bit more context to how the JSON is received. I'm using the ApiAI API to generate a request to their platform, and they have a method to retrieve it, like this:
# instantiate ApiAI
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
# declare a request obect, fill in in lower lines
request = ai.text_request()
# send ApiAI the request
request.query = "{}".format(textobject.body)
# get response from ApiAI
response = request.getresponse()
response_decode = response.read().decode("utf-8")
response_data = json.loads(response_decode)
I'm coding a webapp in Django and trying to read through a JSON response POSTed to a webhook. The code to read through the JSON, after it has been decoded, is:
if response_data['result']['action'] != "":
Request.objects.create(
request = response_data['result']['resolvedQuery']
)
When I try to run this code, I get this error:
KeyError: 'result'
on the line
if response_data['result']['action'] != "":
I'm confused because it looks to me like 'result' should be a valid key to this JSON that is being read:
{
'id':'65738806-eb8b-4c9a-929f-28dc09d6a333',
'timestamp':'2017-07-10T04:59:46.345Z',
'lang':'en',
'result':{
'source':'agent',
'resolvedQuery':'Foobar',
'action':'Baz'
},
'alternateResult':{
'source':'domains',
'resolvedQuery':'abcdef',
'actionIncomplete':False,
},
'status':{
'code':200,
'errorType':'success'
}
}
Is there another way I should be reading this JSON in my program?
Try:
import JSON
if 'action' in response_data:
parsed_data = json.loads(response_data)
if parsed_data['result']['action'] != "":
Request.objects.create(request = parsed_data['result']['resolvedQuery'])
Thanks for everyone's thoughts. It turned out there was an another error with how I was trying to implement the ApiAI API, and that was causing this error. It now reads through the JSON fine, and I'm using #sasuke's suggestion.
I am relatively new to both JSON and Django forms. And I wonder how Djagno's user_form.errors.as_json() should be used to transfer error messages to client-slde. Right now, I have the following code:
On the server-side. I have:
if form.is_valid():
# some code
else:
return JsonResponse(user_form.errors.as_json(), status = 400, safe = False)
Client:
$.post('/url/', data, function(response){
// Success
}).fail(function(response){
var errors = $.parseJSON($.parseJSON(response.responseText)); // looks stupid
The akward line $.parseJSON($.parseJSON(response.responseText)); proves that I am doing something wrong. Can anyone provide a best-practice code pattern for sending and parsing jsonified form errors ?
The problem is that you are You are converting to JSON twice - once when you call as_json, then again when you use JsonResponse.
You could use HttpResponse with form.errors.as_json():
return HttpResponse(user_form.errors.as_json(), status = 400, content_type='application/json')
Note the warnings in the as_json docs about escaping results to avoid a cross site scripting attack. You should ensure the results are escaped if you use JsonResponse as well.
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= ... ")
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