Dolidod Teethtard
Dolidod Teethtard

Reputation: 623

Converting JSON response to python object

I want to convert HTTP GET response (I am using requests library) to python object. Here's my code:

# Full, pure, response
response = requests.get(url)

# Getting request data/content represented in byte array
content = response.content

# Byte array to string
data = content.decode('utf8')


# This line causes "ValueError: malformed node or string: <_ast.Name object at 0x7f35068be128>"
#data = ast.literal_eval(data)

# I tried this also but data is still string after those 2 lines
data = json.dumps(data)
data = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))

Upvotes: 0

Views: 888

Answers (1)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

You can get the response as a dictionary using content = response.json(), and then pass that content to json.loads directly (This is assuming your response comes as a json)

# Full, pure, response
response = requests.get(url)

# Getting response as dictionary
content = response.json()

#Loading dictionary as json
data = json.loads(content, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))

Upvotes: 2

Related Questions