Reputation: 47
I'm running an API query that returns three key value pairs:
{'enabled': True, 'recording': False, 'autoDeletion': False}
I need to replace the values with 1
and 0
respectively, to obtain:
{'enabled': 1, 'recording': 0, 'autoDeletion': 0}
I've tried using json.dumps.replace, but I just get a list of errors from the JSON encoder module, culminating in "TypeError: Object of type Response is not JSON serializable", which is why it's commented out in the code.
Is there a simple way to achieve this seemingly trivial substitution please?
Here's the code
#Make API request
api_response = requests.request("GET", server + query_endpoint, headers=query_headers, data=query_payload)
#api_test = json.dumps(api_response).replace('"true"','"1"')
print(api_response.json())
And the output looks like this:
{'enabled': True, 'recording': False, 'autoDeletion': False}
Upvotes: 1
Views: 316
Reputation: 4923
I think the .json()
return a dict
, then do like this,
data = api_response.json()
for k,v in data.items():
data[k] = int(v)
print(data)
Output:
{'enabled': 1, 'recording': 0, 'autoDeletion': 0}
Hope that works!
Upvotes: 5
Reputation: 22472
You can use a dict comprehension and just cast each value to an int:
api_response_json = {k: int(v) for k, v in api_response.json().items()}
print(api_response_json)
Output:
{'enabled': 1, 'recording': 0, 'autoDeletion': 0}
Upvotes: 3