0

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()))
2
  • content = response.json() ? Commented May 17, 2019 at 6:31
  • Could you show us how your response.text looks like, if it is a valid json object, then only you can perform dumps or loads on it @DolidodTeethtard Commented May 17, 2019 at 6:38

1 Answer 1

2

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()))
Sign up to request clarification or add additional context in comments.

2 Comments

Your answer helped me, but respone.json() returns dict, and I needed to convert it to string with this line content = json.dumps(data)
You don't have that line content = json.dumps(data) in your code in the question. Instead you do data = json.dumps(data) and then data = json.loads(data,, whereas now you have your content as a dictionary, so you only need json.dumps

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.