How to convert python response in string to Json

Viewed 2163

I am trying to return a json response, but all i get is str type response

import json
import requests
def Execute(query):
        try:
        response = requests.post(API_URL, headers=HEADERS,json={'query': query})
        response = json.loads(response)
        if response.status_code == 200:
            return response,200 
        else:
            return response,400             
    except Exception as e:
        return e, 500
2 Answers

You have to get the body of your response before pass it to json.loads, just change the line:

response = json.loads(response)

To:

response = json.loads(response.text)

You can directly get the json object using the following:

response = requests.post(API_URL, headers=HEADERS,json={'query': query})
response_json = response.json()

You don't need to use json.loads().

Related