selecting a key-value from API response - json

I have this response from an API:
payment_object = {'acquirer_response': '{"object":"transaction", "pix_expiration_date":"2022-04-28T13:46:01.000Z"}'}
how can i select the pix_expiration_date key??? I have tried:
payment_object['acquirer_response']['pix_expiration_date']
it doesnt work and it returns to me:
TypeError: string indices must be integers

Since you’re looking for json
Here’s a code you can start with, keep the good work :)
import json
#importing json
payment_object = {'acquirer_response': '{"object":"transaction", "pix_expiration_date":"2022-04-28T13:46:01.000Z"}'}
###
dic=json.loads(payment_object["acquirer_response"])
#loading the object
dic['pix_expiration_date']
#it will return 2022-04-28T13:46:01.000Z

Are you the owner of the api? If yes:
Edit the response, because it’s sending an string not an object/dictionary
If No:
Convert the string to an dictionary, like if you using python try json library

Your json is not valid. I don't know what language are you using, this code works for javascript, you can easily translate it to another language
var payment_object = {'acquirer_response': '{"object":"transaction", "pix_expiration_date":"2022-04-28T13:46:01.000Z"}'};
var s=JSON.stringify(payment_object).replaceAll("\\","").replaceAll("\"{","{").replaceAll("}\"","}");
var paymentObject=JSON.parse(s);
console.log(paymentObject['acquirer_response']['pix_expiration_date']); // 2022-04-28T13:46:01.000Z

Related

Is there a way to define a to_json handler in GDScript?

I'm new to GDScript and am looking at how best to save data to a text file. to_json works well for basic types but I just get a reference id for any custom classes. I'd ideally like to pass a dictionary of data including some custom class elements to to_json and let it convert it all at once.
Like other languages provide a toString method for printing an object, is there anything that would let me specify how a class instance should be converted to JSON?
Yeah, you would just add something like the following to your class:
func to_json():
var data = {} #must create it as a dictionary or array
data["health"] = 5
#code to create json
var json
json = data.to_json() #dictionaries automatically have this function
return json
I think it really is that simple :)
Please note: I have not tested this code.

Is this a correct JSON? How we can parse it?

My web service is returning below mentioned output as JSON,
{"FetchSitePerformanceAutoResult":[{"DailyTimeStamp":"Nov 01, 2013","Performance":106917}]}
But I doubt cause I am not able to parse it.
If it is correct pls tell me how to parse it? I want to bind it to chart.
Full code
var retVal = '{"FetchSitePerformanceAutoResult":[{"DailyTimeStamp":"Nov 01, 2013","Performance":106917},{"DailyTimeStamp":"Nov 02, 2013","Performance":119542}]}';
alert('Before parsing ' + retVal);
var passValue = JSON.parse(retVal);
alert('After parsing Count ' + passValue.count);
last alert give output as After parsing Count undefined.
The simplest way to parse your json in javascript is that you store it inside a variable and can proceed like this:
var jsonString=JSON.parse(yourJsonString);
then you can fetch each key and their value accordingly.
Just check your json on JsonEditoronline.org for a better way of reading this.
This is sample of how I read my json in javascript:
success:function(responseText)
{
alert(responseText);
return false;
var object= JSON.parse(responseText);
var response= object.response;
var div=$('<div></div>');
var docs= response.docs;
where my json was something like this:
{"response":{"docs":""}}
Hope it helps.
I parsed your json using javascript and was able to parse it using :
var myString='{"FetchSitePerformanceAutoResult":[{"DailyTimeStamp":"Nov 01, 2013","Performance":106917}]}';
var jsonString=JSON.parse(myString);
alert("---------==="+jsonString);
var fetch= jsonString.FetchSitePerformanceAutoResult;
alert("llllllll -- "+fetch.length);
var time= fetch[0].DailyTimeStamp;
alert(time);
To tell if JSON is correct, you can use http://jsonlint.com/ Your JSON is correct. To parse it, use the .net JSON Deserializer http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx or JSON.NET Also see here for some discussion: Does .NET 4 have a built-in JSON serializer/deserializer?
EDIT: as you want Javascript, use JSON.parse. See some discussion here: http://www.json.org/js.html which also explains why you should not use eval(json), which does also work, but is considered a security risk.
Yes your json output is correct and you can check yourself here is the Link, this will help you convert your json to c# class. Hope this helps.
That is a valid JSON String. You can check it at http://jsonlint.com/
It is legal - php json_decode('{"FetchSitePerformanceAutoResult":[{"DailyTimeStamp":"Nov 01, 2013","Performance":106917}]}'); parses it fine.

Standardized way to serialize JSON to query string?

I'm trying to build a restful API and I'm struggling on how to serialize JSON data to a HTTP query string.
There are a number of mandatory and optional arguments that need to be passed in the request, e.g (represented as a JSON object below):
{
"-columns" : [
"name",
"column"
],
"-where" : {
"-or" : {
"customer_id" : 1,
"services" : "schedule"
}
},
"-limit" : 5,
"return" : "table"
}
I need to support a various number of different clients so I'm looking for a standardized way to convert this json object to a query string. Is there one, and how does it look?
Another alternative is to allow users to just pass along the json object in a message body, but I read that I should avoid it (HTTP GET with request body).
Any thoughts?
Edit for clarification:
Listing how some different languages encodes the given json object above:
jQuery using $.param: -columns[]=name&-columns[]=column&-where[-or][customer_id]=1&-where[-or][services]=schedule&-limit=5&return=column
PHP using http_build_query: -columns[0]=name&-columns[1]=column&-where[-or][customer_id]=1&-where[-or][services]=schedule&-limit=5&return=column
Perl using URI::query_form: -columns=name&-columns=column&-where=HASH(0x59d6eb8)&-limit=5&return=column
Perl using complex_to_query: -columns:0=name&-columns:1=column&-limit=5&-where.-or.customer_id=1&-where.-or.services=schedule&return=column
jQuery and PHP is very similar. Perl using complex_to_query is also pretty similar to them. But none look exactly the same.
URL-encode (https://en.wikipedia.org/wiki/Percent-encoding) your JSON text and put it into a single query string parameter. for example, if you want to pass {"val": 1}:
mysite.com/path?json=%7B%22val%22%3A%201%7D
Note that if your JSON gets too long then you will run into a URL length limitation problem. In which case I would use POST with a body (yes, I know, sending a POST when you want to fetch something is not "pure" and does not fit well into the REST paradigm, but neither is your domain specific JSON-based query language).
There is no single standard for JSON to query string serialization, so I made a comparison of some JSON serializers and the results are as follows:
JSON: {"_id":"5973782bdb9a930533b05cb2","isActive":true,"balance":"$1,446.35","age":32,"name":"Logan Keller","email":"logankeller#artiq.com","phone":"+1 (952) 533-2258","friends":[{"id":0,"name":"Colon Salazar"},{"id":1,"name":"French Mcneil"},{"id":2,"name":"Carol Martin"}],"favoriteFruit":"banana"}
Rison: (_id:'5973782bdb9a930533b05cb2',age:32,balance:'$1,446.35',email:'logankeller#artiq.com',favoriteFruit:banana,friends:!((id:0,name:'Colon Salazar'),(id:1,name:'French Mcneil'),(id:2,name:'Carol Martin')),isActive:!t,name:'Logan Keller',phone:'+1 (952) 533-2258')
O-Rison: _id:'5973782bdb9a930533b05cb2',age:32,balance:'$1,446.35',email:'logankeller#artiq.com',favoriteFruit:banana,friends:!((id:0,name:'Colon Salazar'),(id:1,name:'French Mcneil'),(id:2,name:'Carol Martin')),isActive:!t,name:'Logan Keller',phone:'+1 (952) 533-2258'
JSURL: ~(_id~'5973782bdb9a930533b05cb2~isActive~true~balance~'!1*2c446.35~age~32~name~'Logan*20Keller~email~'logankeller*40artiq.com~phone~'*2b1*20*28952*29*20533-2258~friends~(~(id~0~name~'Colon*20Salazar)~(id~1~name~'French*20Mcneil)~(id~2~name~'Carol*20Martin))~favoriteFruit~'banana)
QS: _id=5973782bdb9a930533b05cb2&isActive=true&balance=$1,446.35&age=32&name=Logan Keller&email=logankeller#artiq.com&phone=+1 (952) 533-2258&friends[0][id]=0&friends[0][name]=Colon Salazar&friends[1][id]=1&friends[1][name]=French Mcneil&friends[2][id]=2&friends[2][name]=Carol Martin&favoriteFruit=banana
URLON: $_id=5973782bdb9a930533b05cb2&isActive:true&balance=$1,446.35&age:32&name=Logan%20Keller&email=logankeller#artiq.com&phone=+1%20(952)%20533-2258&friends#$id:0&name=Colon%20Salazar;&$id:1&name=French%20Mcneil;&$id:2&name=Carol%20Martin;;&favoriteFruit=banana
QS-JSON: isActive=true&balance=%241%2C446.35&age=32&name=Logan+Keller&email=logankeller%40artiq.com&phone=%2B1+(952)+533-2258&friends(0).id=0&friends(0).name=Colon+Salazar&friends(1).id=1&friends(1).name=French+Mcneil&friends(2).id=2&friends(2).name=Carol+Martin&favoriteFruit=banana
The shortest among them is URL Object Notation.
How about you try this sending them as follows:
http://example.com/api/wtf?
[-columns][]=name&
[-columns][]=column&
[-where][-or][customer_id]=1&
[-where][-or][services]=schedule&
[-limit]=5&
[return]=table&
I tried with a REST Client
And on the server side (Ruby with Sinatra) I checked the params, it gives me exactly what you want. :-)
Another option might be node-querystring. It also uses a similar scheme to the ones you've so far listed.
It's available in both npm and bower, which is why I have been using it.
Works well for nested objects.
Passing complex objects as query parameters of a url.
In the example below, obj is the JSON object to pass into query parameters.
Injecting JSON object as query parameters:
value = JSON.stringify(obj);
URLSearchParams to convert a string to an object representing search params. toString to retain string type for appending to url:
queryParams = new URLSearchParams(value).toString();
Pass the query parameters using template literals:
url = `https://some-url.com?key=${queryParams}`;
Now url will contain the JSON object as query parameters under key (user-defined name)
Extracing JSON from url:
This is assuming you have access to the url (either as string or URL object)
url_obj = new URL(url); (only if url is NOT a URL object, otherwise ignore this step)
Extract all query parameters in the url:
queryParams = new URLSearchParams(url_obj.search);
Use the key to extract the specific value:
obj = JSON.parse(queryParams.get('key').slice(0, -1));
slice() is used to extract a tailing = in the query params which is not required.
Here obj will be the same object passed in the query params.
I recommend to try these steps in the web console to understand better.
You can test with JSON examples here: https://json.org/example.html

how to get individual valued from the json array..?

I got json array as output. could anyone explain me how to get indivual value from it for eg( C:/). The following is the json array
{"Name":["C:\/","D:\/","E:\/","F:\/","G:\/","My Documents","Microsoft Outlook","Microsoft Outlook Express","Opera","Mozilla","Internet Explorer Settings","FireFox","Desktop","Registry","SystemState"],"path":["C:\/","D:\/","E:\/","F:\/","G:\/","\/\/\/My Documents\/\/\/","\/\/\/Microsoft Outlook\/\/\/","\/\/\/Microsoft Outlook Express\/\/\/","\/\/\/Opera\/\/\/","\/\/\/Mozilla\/\/\/","\/\/\/Internet Explorer Settings\/\/\/","\/\/\/FireFox\/\/\/","\/\/\/Desktop\/\/\/","\/\/\/Registry\/\/\/","\/\/\/SystemState\/\/\/"],"hasChild":["1","1","1","1","1","0","0","0","0","0","0","0","0","0","0"]}
Assuming your language is JavaScript, you first need to parse the JSON (below I use jQuery's $.parseJSON method) and then access the appropriate property and array position. To retreive "C:\", you would do this:
var sJSON = '{"Name":["C:\/","D:\/","E:\/","F:\/","G:\/","My Documents"]}';
var oJSON = $.parseJSON(sJSON);
alert(oJSON.Name[0]); //displays C:\
If you're using JavaScript, you can use an eval() statement in place of a $.parseJSON because JSON is executable in JavaScript, but it is safer to use a $.parseJSON.
More on JavaScript eval(): When is JavaScript's eval() not evil?
Use a JSON parsing library for your language.
In JavaScript, you can use JSON.parse. If your output is in the var output, you would do:
var obj = JSON.parse(output);
console.log(obj.path[0]);

Could not retrieve json data from the given format

this is my json format
({"message":{"success":true,"result":[{"lead_no":"LEA13","lastname":"Developer","firstname":"PHP","company":"Dummies","email":"nandhajj#gmail.com","id":"10x132"},{"lead_no":"LEA14","lastname":"Venu","firstname":"Yatagiri","company":"Rsalesarm","email":"veve#jajs.com","id":"10x133"},{"lead_no":"LEA4","lastname":"Jones","firstname":"Barbara","company":"Vtigercrm inc","email":"barbara_jones#company.com","id":"10x35"},{"lead_no":"LEA1","lastname":"Smith","firstname":"Mary","company":"Vtiger","email":"mary_smith#company.com","id":"10x32"}]}})
i am trying to retrieve the whole json result values using the following snippet
if (xmlHttp.readyState==4)
{
alert(xmlHttp.status);
if(xmlHttp.status==200)
{
alert("hi");
var jsondata=eval("("+xmlHttp.responseText+")") //retrieve result as an JavaScript object
jsonOutput=jsondata.result;
alert(jsonOutput);
InitializeLeadStorage()
}
}
my alert (hi ) is displayed but the alert(jsonOutput); is undefined , please help me if you could find any mistake
jsonOutput = jsondata.message.result;
result lives on message - it is not a top-level item in the JSON. With things like this, console.log() the JSON and you can check the path to the bit you want.
Also
your variable is global
there are better ways of parsing your JSON. If you don't care about old IEs, you can use the ECMA5 JSON.parse(), else use jQuery or another third-party utility for this