Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access json data in django?

Tags:

json

django

I want to access session_key from JSON response. In login api I am sending credential it response back with Content-Type: application/json I need to access session_key. How to access session_key for json response.

credential["username"]="john"
credential["password"]="xxx"
response =c.put('/api/login', data=json.dumps(credential))

JSON Respone

  print response.content

output

{"message": "", "result": {"username": "john", "session_key": "xyx"}}

When I tried to use print(response.content.result) getting error AttributeError: 'str' object has no attribute 'result'

like image 497
Neelabh Singh Avatar asked Oct 31 '25 19:10

Neelabh Singh


2 Answers

If response.content is json you just have to decode it to a python dict.

import json

content = json.loads(response.content)
key = content['result']['session_key']
like image 154
Laraconda Avatar answered Nov 02 '25 11:11

Laraconda


In request.content you have json data.. you have to get that data to python dict..

You can try this:

json.loads(response.content)['result']['session_key']

or if you use requests:

response.content.json()['result']['session_key']
like image 31
Sławek Kabik Avatar answered Nov 02 '25 11:11

Sławek Kabik