Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse JSON Array of objects in python

Tags:

python

json

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?

like image 443
Arul Avatar asked Dec 02 '22 11:12

Arul


2 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'])
like image 87
Jim Wright Avatar answered Dec 04 '22 07:12

Jim Wright


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": "[email protected]",
    "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": "[email protected]",
    "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: [email protected]
ID: pbjds5wmsp8cxr993nmc6ozodh

Name: chatops
Email: [email protected]
ID: akxdddp5p7fjirxq7whhntq1nr
like image 25
MITHU Avatar answered Dec 04 '22 08:12

MITHU