I received the following JSON Array from the POST response of an HTTP request:

[{ "username": "username_1", "first_name": "", "last_name": "", "roles": "system_admin system_user", "locale": "en", "delete_at": 0, "update_at": 1511335509393, "create_at": 1511335500662, "auth_service": "", "email": "userid_1@provider_1.com", "auth_data": "", "position": "", "nickname": "", "id": "short-string-of-random-characters-1" }, { ... } <more such objects>..] 

Given that typeof(response) gives me requests.models.Response, how can I parse it in Python?

4

4 Answers

Take a look at the json module. More specifically the 'Decoding JSON:' section.

import json import requests response = requests.get() # api call users = json.loads(response.text) for user in users: print(user['id']) 
2

You can try like below to get the values from json response:

import json content=[{ "username": "admin", "first_name": "", "last_name": "", "roles": "system_admin system_user", "locale": "en", "delete_at": 0, "update_at": 1511335509393, "create_at": 1511335500662, "auth_service": "", "email": "", "auth_data": "", "position": "", "nickname": "", "id": "pbjds5wmsp8cxr993nmc6ozodh" }, { "username": "chatops", "first_name": "", "last_name": "", "roles": "system_user", "locale": "en", "delete_at": 0, "update_at": 1511335743479, "create_at": 1511335743393, "auth_service": "", "email": "", "auth_data": "", "position": "", "nickname": "", "id": "akxdddp5p7fjirxq7whhntq1nr" }] for item in content: print("Name: {}\nEmail: {}\nID: {}\n".format(item['username'],item['email'],item['id'])) 

Output:

Name: admin Email: ID: pbjds5wmsp8cxr993nmc6ozodh Name: chatops Email: ID: akxdddp5p7fjirxq7whhntq1nr 
1

It seems what you are looking for is the json module. with it you can use this to parse a string into json format:

import json output=json.loads(myJsonString) 

use python 3 and import urlib

import urllib.request import json url = link of the server #Taking response and request from url r = urllib.request.urlopen(url) #reading and decoding the data data = json.loads(r.read().decode(r.info().get_param('charset') or 'utf-8')) for json_inner_array in data: for json_data in json_inner_array: print("id: "+json_data["id"]) 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy