1

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}
1
  • >>> d = {'enabled': True, 'recording': False, 'autoDeletion': False} >>> {k: 1 if v else 0 for k, v in d.items()} {'enabled': 1, 'recording': 0, 'autoDeletion': 0} Commented Nov 27, 2020 at 12:16

2 Answers 2

5

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!

Sign up to request clarification or add additional context in comments.

Comments

3

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}

1 Comment

Thanks gents. That seems to have done it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.