unable to serialize json array - python

I am somewhat new to working with API's and am receiving a graphconnection is not serializable error when trying to json.dumps an api response. The response looks to be a json array however, when i run Type(api_response) nothing is output.
Any help would be appreciated.
I have tried Type(api_response)
api_response = api_instance.graph_user_group_members_list(group_id, content_type, accept,limit=limit, skip=skip, x_org_id=x_org_id)
#pprint(api_response)
data = json.dumps(api_response)
I would like to convert the api_response to python dict format so that I can use the json values....
I am receiving this error
TypeError: Object of type GraphConnection is not JSON serializable
This is the output if I print api_response
[{'_from': None, 'to': {'id': '', 'type': 'user'}}, {'_from': None,
'to': {'id': '', 'type': 'user'}}]

It's likely because of the brackets around the json object. The data within the curly braces is valid json. Try to index the api_response (like jsonObject = api_response[0]) to get the 'first element' of the api response object.

I actually was able to find the solution by using ([ob.dict for ob in api_response]). Still think I am missing some knowledge surrounding how json.dumps works.

Related

How to post json data directly in Rest API with python

I have a response data which is in json format, now I want to post this json format.But I have issues with same.
{'u_correlationid_': '', 'resolved_by': '','active': 'true', 'upon_approval': 'proceed', 'skills': '', 'parent_incident': '', 'business_impact': '', 'sys_domain': {'value': 'global', 'link': ''}, 'made_sla': 'true', 'activity_due': '2019-11-07 10:09:15', 'opened_at': '2019-09-11 16:17:24'}
When I tried directly posting the json data I had error:
"error": "Validation error - JSON parse error: Can not deserialize instance of java.lang.String out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token\n at [Source: java.io.PushbackInputStream#37b90445; line: 1, column: 298] (through reference chain: java.util.LinkedHashMap[\"sys_domain\"])"
I want to fix this error in Python and also post my json data with " instead of ' format of my response
E.g-{"u_correlationid":""} and at last I also want to append one key pair to existing before post.
E.g-
{"u_correlationid":"",
"opened_at": "2019-09-11 16:17:24","data":"big"}

JSON not working from Google Finance

I am trying to extract information from a JSON file from Google Finance. The requests.get() is working but then I get stuck. I have searched quite a bit and nothing suggested seems to work. This is what I have:
import requests
from json import loads
params={'q': 'NASDAQ:AAPL','output': 'json'}
response = requests.get('https://finance.google.com/finance', params=params, allow_redirects=False, timeout=10.0)
print(response.status_code)
print(response.content)
The output is “200” which is the ok output I believe. print(response.content) gives me the full JSON string so that seems to be working ok.
However, trying to pass it into “data” so that I can work with further, extract various bits. This is what I have tried:
data = response.json() gives me JSONDecodeError: Expecting value: line 2 column 1 (char 1)
data = json.load(response) gives me AttributeError: 'Response' object has no attribute 'read'
data = json.loads(response) gives me TypeError: the JSON object must be str, bytes or bytearray, not 'Response'
I tried data = json.loads(response.decode("utf-8")) and that gives me AttributeError: 'Response' object has no attribute 'decode'. I have also tried some text scrubbing suggestions, nothing has worked yet.
I printed the text. and I found that first some data is not json string...
\n // chars...
jsonstr = response.text[4:] #remove first part (not json data)
data = loads(jsonstr)
print(data)
print("t=",data[0]['t'])
output
[{'t': 'AAPL', 'kr_annual_date': '2017', 'hi': '180.52', 'keyratios': [{'title': 'Net profit margin', 'annual': '21.09%', 'recent_quarter': '25.67%', 'ttm': '22.21%'}, {'title': 'Operating margin', 'annual': '26.76%', 'rece ....
....
com/'}]}]
t= AAPL
Try using response.content or response.text to convert to JSON.
Ex:
json.loads(response.content)
or
json.loads(response.text)

Sending a variable as data parameter in requests.post() in Python

I'm trying to pass a variable to the data field in requests.post() and I continue to get the error,
Error Response: {'error': {'message': 'Exception while reading request',
'detail': 'Cannod decode: java.io.StringReader#1659711'}, 'status': 'failure'}
Here is my code
#Fill array from CSV
temp=[]
for row in csv.iterrows():
index, data = row
temp.append(data.tolist())
#Create new asset for all assets in CSV
for index, row in enumerate(temp):
make = temp[index][0]
serial = str(temp[index][1])
date = str(temp[index][2])
response = requests.post(url, auth=(user, pwd), headers=headers,
data='{"asset_tag":"test1", "assigned_to":"test2",
"company":"test3", "serial_number":serial}')
I originally tried feeding it directly from the CSV using
str(temp[index][1])
This did not work, so I tried assigning str(temp[index][1]) to the variable serial and then passing the variable like that but that also results in the same error.
A point in the right direction would be great, thanks!
Instead of sending the request payload body in string, pass it in json form.
requests.post accepts string in data variable and json in json variable. I faced a same issue while trying to make my first REST call to ServiceNow instance via Python. Hope this helps.
response = requests.post(url, auth=(user, pwd), headers=headers,
json={"asset_tag":"test1", "assigned_to":"test2",
"company":"test3", "serial_number":serial})
Remove the single quotes from the following :
data='{"asset_tag":"test1", "assigned_to":"test2",
"company":"test3", "serial_number":serial}'
Use
data = {"asset_tag":"test1", "assigned_to":"test2",
"company":"test3", "serial_number":serial}
rather than passing data=data, take data as dict and pass it as json=data.

Flask.json_encode, TypeError: __init__() got an unexpected keyword argument

I'm getting started with flask. I'm trying to return some json from a flask app which I want to generate from a dictionary:
My code looks like:
resp = views.calculate(d)
print type(resp)
print resp
return Flask.json_encoder(**resp)
The output:
<type 'dict'>
{'target1': 'DOES NOT EXIST', 'stage': 0, 'token': u'fsdfsdf', 'target2': 'DOES NOT EXIST', 'text': ''}
and finally I get The error above. How can I fix this?
Flask.json_encoder is the class used to encode JSON with. It does not accept keyword arguments, nor would calling it produce JSON directly.
To produce a response with JSON encoded data, use flask.jsonify() instead:
from flask import jsonify
return jsonify(**resp)
If all you need is the JSON string, use flask.json.dumps() here, passing in the dictionary (and not keyword arguments):
from flask import json
return json.dumps(resp)
In both cases the class referenced by Flask.json_encoder (via the app instance) would be used to produce the JSON encoding.

Using python 'requests' to send JSON boolean

I've got a really simple question, but I can't figure it out how to do it. The problem I have is that I want to send the following payload using Python and Requests:
{ 'on': true }
Doing it like this:
payload = { 'on':true }
r = requests.put("http://192.168.2.196/api/newdeveloper/lights/1/state", data = payload)
Doesn't work, because I get the following error:
NameError: name 'true' is not defined
Sending the true as 'true' is not accepted by my server, so that's not an option. Anyone a suggestion? Thanks!
You need to json encode it to get it to a string.
import json
payload = json.dumps({"on":True})
should be {'on': True}, capital T
Starting from requests 2.4.2, instead of passing in the payload with the data parameter, you can use the json parameter like this:
payload = {'on': True}
requests.put(url, json=payload)
And the request will be formatted correctly as a json payload (i.e. {'on': true}).
to make it be lower case like that (if that's what your endpoint requires) do in quotes {'on':'true'}

Categories

Resources