This is my code for the elasticsearch, throws an error of json not serializable when we try to json.dumps
ret = es.indices.create(index='wiki-index', ignore=400, mappings=b)
print("ret: ", type(ret))
print(json.dumps(ret, indent=4))
I tried converting the ret to_dict() and ignore 400 added
Related
i'm having an issue while write codes for consume another API using Python + Flask + Requests.
their API using PHP with x-www-form-urlencoded instead of RAW JSON, here is my code :
app = Flask(__name__)
#app.route('/api/test/getinfo', methods=['POST'])
def get_house_info():
if request.method == 'POST':
try:
payloads = {'no_house':'001234123', 'cd_agent' : '01', 'nm_agent' : 'ABC'}
response_data = requests.post(url=url, headers=headers, data=payloads)
return response_data
except Exception as e:
return(str(e))
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
after that i run this flask and tried to call this endpoint using postman
but i received error Object of type Response is not JSON serializable is there something wrong in my codes ?
Try json.dumps() for payloads
python dictionary and json is not the same, refer to its usage here:
Note: Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys. source
From python to json : json.dumps(x)
From json to python : json.loads(x)
I am requesting an api and get the following response and not getting my results.
For IDE I am using pycharm community edition.
import requests
import json
def tes():
url="https://user-service.abc.co.in/api/user/admin/roles/"
header ={'Content-Type': 'application/json' }
payload ={'phone_number': '9999999999'}
resp=requests.get(url,headers=header,data=json.dump(payload,indent=4))
assert resp.status_code==200
resp_body=resp.json()
assert resp_body['url']==url
print(resp.text)
Please help me why this is happening.
In the line resp=requests.get(url,headers=header,data=json.dump(payload,indent=4)) you are trying to convert the payload to json but you called json.dump() which expects a file-like object as second parameter. From the docs:
json.dump(obj, fp)
Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) Python docs for json.dump()
For your purposes you want to use json.dumps(obj) (notice the 's' at the end) which
Serialize obj to a JSON formatted str
Python docs for json.dumps()
I'm trying to read the response from an API, but whenever I try to access the JSON elements _ keep getting errors like:
...
...
print(parsed_data['result']['listing']['whisper'])
TypeError: list indices must be integers or slices, not str
My current code looks like:
import json
import requests
from bs4 import BeautifulSoup
item_data_api = "https://www.pathofexile.com/api/trade/fetch/e6c3075c2bea510e868dd9568930c74cfd7d926e2dc74dd12b1119ecb565b3ff"
r = requests.get(item_data_api)
if r.status_code == 200:
print(r.encoding)
parsed_data = r.json()
print(parsed_data)
print(parsed_data['result']['listing']['whisper'])
If I get the output from print and validate the JSON on https://jsonlint.com/, it is not valid:
Error: Parse error on line 1:
[{ 'id': 'e6c3075c2bea5
---^
Expecting 'STRING', '}', got 'undefined'
However, if I execute the call in a browser, the response is valid.
What am I missing here? Can someone please provide a hint on how to make the output valid? I already tried json.loads(r.text) but doesn't work either.
In this case the issues is the data you are being returned is not in the format you are expecting.
This line:
print(parsed_data['result']['listing']['whisper'])
assumes that you are getting a dictionary that looks like:
result = {
"results": {
"listing": {
"whisper": ...}}}
That's not what is being returned, it's more like:
result = {
"results": [
{"listing": ... }
{"listing": ... }]}
So results is actually returning a list of dictionaries, which is why you get the error - you can't index into a list using a string.
If I run your code, and pull out the first results dictionary I don't get your error:
print(parsed_data['result'][0]['listing']['whisper'])
I'm trying to get a parameter from a JSON string loaded with requests.
I think I tried any combination I can think of.
Any hints are very appreciated.
My code is this:
r = requests.get(url, headers=headers)
json_string = r.json
status = json.dumps(json_string['httpStatusCode'])
and I'm getting
'method' object is not subscriptable
The error you are getting because you are assigning a "method" object to json_string.Since in python "method" objects are not subscriptable.
To get JSON response you have to do this
json_string = r.json()
I'm querying an API for some JSON formatted data but it is coming back with slightly invalid formatting. There is a preceding comma which is causing a problem, I was wondering if there was any way around this?
I'm using the Requests library to issue the API queries and read the JSON like so:
resp = requests.get(citedByURL % (eid, apiKey, citedByPerPage, startPoint))
data = resp.json()
The JSON has an error which you can see here:
"entry": [{, "link": [{"#ref": "self", "#href": "http://api.elsevier.com/content/abstract/scopus_id/77957867010"}
And hence Python throws the following error:
ValueError: Expecting property name enclosed in double quotes: line 1 column 1164 (char 1163)
Is there anything I can do to maybe preprocess the data before attempting to load it as JSON?
resp = requests.get(citedByURL % (eid, apiKey, citedByPerPage, startPoint))
data = resp.text()
data = data.replace("[{,", "[{")
data = json.loads(data)