Hướng dẫn python parse json array - python phân tích mảng json

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

Deserialize kiểu dữ liệu complex

Serialize và deserialize các user-defined class

Với những class tự định nghĩa, bạn có thể tận dùng thuộc tính

{                                                                      
   "name": "Guido van Rossum",
   "age": 65,
   "degree": ["mathematics", "computer science"],
   "retired": true,
	"carrer": {
		"google":{
			"from": 1999,
			"to": 2013
		},
		"dropbox": {
			"from": 2013,
			"to": 2019
		}
}

}
2 để serialize và desialize dữ liệu.
{                                                                      
   "name": "Guido van Rossum",
   "age": 65,
   "degree": ["mathematics", "computer science"],
   "retired": true,
	"carrer": {
		"google":{
			"from": 1999,
			"to": 2013
		},
		"dropbox": {
			"from": 2013,
			"to": 2019
		}
}

}
2 trả ra một dictionary chứa các thuộc tính của đối tượng đó.

{                                                                      
   "name": "Guido van Rossum",
   "age": 65,
   "degree": ["mathematics", "computer science"],
   "retired": true,
	"carrer": {
		"google":{
			"from": 1999,
			"to": 2013
		},
		"dropbox": {
			"from": 2013,
			"to": 2019
		}
}

}

Ký tự

{                                                                      
   "name": "Guido van Rossum",
   "age": 65,
   "degree": ["mathematics", "computer science"],
   "retired": true,
	"carrer": {
		"google":{
			"from": 1999,
			"to": 2013
		},
		"dropbox": {
			"from": 2013,
			"to": 2019
		}
}

}
4 trong decode_data = People(**json.loads(encode_data)) là cú pháp đặc biệt của python, để truyền một danh sách các keyword argument vào hàm.

Tổng kết Ngoài json, các định dạng file xml và yaml cũng được dùng để lưu trữ và trao đổi dữ liệu. Tuy nhiên, json ngày càng trở nên phổ biến hơn, vì những ưu điểm nó mang lại.

Như vậy, chúng ta đã cùng nhau đi qua tổng thể cách làm việc với định dạng json trong python. Ta có một vài kết luận rút gọn như sau:

Json là một chuẩn định dạng file được sử dụng phổ biến để lưu trữ và trao đổi thông tin

Serialize là quá trình chuyển một object trong chương trình về dạng mà máy tính có thể lưu trữ hoặc truyền đi được. Trong python, để serialize dữ liệu, ta dùng json.dump() hoặc json.dumps()

Deserialize là quá trình khôi phục lại các object từ file json hoặc chuỗi các bit nhận được từ mạng. Trong python, để deserialize dữ liệu, ta dùng json.load() hoặc json.loads()

Deserialize định dạng json

Từ phiên bản 2.6, Python đã bổ sung module json vào thư viện chuẩn. Do vậy, nếu phiên bản python của bạn cao hơn, để làm việc với json, bạn chỉ cần import module này vào. Nếu sử dụng phiên bản python thấp hơn, bạn có thể sử dụng pip để cài đặt gói này. Tuy nhiên, mình khuyến khích các bạn nên nâng cấp python lên phiên bản cao hơn, vì python 2.x đã không còn được hỗ trợ nữa.

import json

Trong quá trình deserialize, ta cần chuyển đổi từ json type sang python type. Bảng chuyển đổi tương ứng như sau:

Json Python
object dict
array list
string str
number(int) int
number(real) float 
true True
false False
null None 

Để deserialize một file json sang dạng object, ta dùng hàm load. Ví dụ với file

{                                                                      
   "name": "Guido van Rossum",
   "age": 65,
   "degree": ["mathematics", "computer science"],
   "retired": true,
	"carrer": {
		"google":{
			"from": 1999,
			"to": 2013
		},
		"dropbox": {
			"from": 2013,
			"to": 2019
		}
}

}
0 nêu ở trên

with open("people.json", "r") as fin:
    data = json.load(fin)
print(data)
>>> {'name': 'Guido van Rossum', 'age': 65, 'degree': ['mathematics', 'computer science'], 'retired': True, 'carrer': {'google': {'from': 1999, 'to': 2013}, 'dropbox': {'from': 2013, 'to': 2019}}}
print(type(data))
>>> 
print(type(data['age']))
>>> 
print(type('carrer'))
>>> 

Ta cũng có thể deserialize một json string, dùng hàm loads.

json_string = """
{
	"name": "Guido van Rossum",
	"age": 65,
	"degree": ["mathematics", "computer science"],
	"retired": true,
	"carrer": {
		"google":{
			"from": 1999,
			"to": 2013
		},
		"dropbox": {
			"from": 2013,
			"to": 2019
		}
	}
}
"""
data = json.loads(json_string)
print(data)
>>> {'name': 'Guido van Rossum', 'age': 65, 'degree': ['mathematics', 'computer science'], 'retired': True, 'carrer': {'google': {'from': 1999, 'to': 2013}, 'dropbox': {'from': 2013, 'to': 2019}}}
print(type(data))

Sau khi deserialize thành các object xong, bây giờ bạn có thể sử dụng chúng như bình thường.

print(len(data['degree']))
>>> 2
print(data['degree'][0])
>>> mathematics
print(data['age'] + 3)
>>> 68

Serialize python object sang json

Trong quá trình serialize, ta cần chuyển từ kiểu dữ liệu của python sang kiểu dữ liệu của json. Bảng chuyển đổi tương ứng như sau:

Python Json
dict object
dict array
str string
str number(int)
True true
False false
False null

None 

data = {'name': 'Guido van Rossum', 'age': 65, 'degree': ['mathematics', 'computer science'], 'retired': True, 'carrer': {'google': {'from': 1999, 'to': 2013}, 'dropbox': {'from': 2013, 'to': 2019}}}
with open("people.json", "w") as fout:
    json.dump(data, fout)

Để deserialize một file json sang dạng object, ta dùng hàm load. Ví dụ với file

{                                                                      
   "name": "Guido van Rossum",
   "age": 65,
   "degree": ["mathematics", "computer science"],
   "retired": true,
	"carrer": {
		"google":{
			"from": 1999,
			"to": 2013
		},
		"dropbox": {
			"from": 2013,
			"to": 2019
		}
}

}
0 nêu ở trên

data = {'name': 'Guido van Rossum', 'age': 65, 'degree': ['mathematics', 'computer science'], 'retired': True, 'carrer': {'google': {'from': 1999, 'to': 2013}, 'dropbox': {'from': 2013, 'to': 2019}}}
json_string = json.dumps(data)
print(json_string)
>>> {"name": "Guido van Rossum", "age": 65, "degree": ["mathematics", "computer science"], "retired": true, "carrer": {"google": {"from": 1999, "to": 2013}, "dropbox": {"from": 2013, "to": 2019}}}
print(type(json_string)
>>> 
json_string_2 = json.dumps(data, indent=4)
print(json_string_2)
>>> {
    "name": "Guido van Rossum",
    "age": 65,
    "degree": [
        "mathematics",
        "computer science"
    ],
    "retired": true,
    "carrer": {
        "google": {
            "from": 1999,
            "to": 2013
        },
        "dropbox": {
            "from": 2013,
            "to": 2019
        }
    }
}

Ta cũng có thể deserialize một json string, dùng hàm loads.

Sau khi deserialize thành các object xong, bây giờ bạn có thể sử dụng chúng như bình thường.

z = 3 + 2j
print(type(z))
>>> 
json.dumps(z)
>>> TypeError: Object of type complex is not JSON serializable

Serialize python object sang json

Trong quá trình serialize, ta cần chuyển từ kiểu dữ liệu của python sang kiểu dữ liệu của json. Bảng chuyển đổi tương ứng như sau:

Name: admin
Email: 
ID: pbjds5wmsp8cxr993nmc6ozodh

Name: chatops
Email: 
ID: akxdddp5p7fjirxq7whhntq1nr
0

list, tuple

Name: admin
Email: 
ID: pbjds5wmsp8cxr993nmc6ozodh

Name: chatops
Email: 
ID: akxdddp5p7fjirxq7whhntq1nr
1

int, long, float

number

Name: admin
Email: 
ID: pbjds5wmsp8cxr993nmc6ozodh

Name: chatops
Email: 
ID: akxdddp5p7fjirxq7whhntq1nr
2

None

null 

Để lưu một Python object lại dưới dạng file json, ta dùng hàm

{                                                                      
   "name": "Guido van Rossum",
   "age": 65,
   "degree": ["mathematics", "computer science"],
   "retired": true,
	"carrer": {
		"google":{
			"from": 1999,
			"to": 2013
		},
		"dropbox": {
			"from": 2013,
			"to": 2019
		}
}

}
1.

  • Hoặc nếu bạn chỉ cần chuyển một python object sang string json, dùng hàm dumps. Hàm dumps và dump cũng cung cho bạn thêm tham số indent để xâu kết quả nhìn đẹp mắt hơn.
  • Xử lý những object mà module json không hỗ trợ
  • Module json hỗ trợ hầu hết các kiểu dữ liệu được xây dựng sẵn (built-in types), cũng có nghĩa có một vài kiểu dữ liệu mà module này không hỗ trợ, complex là một trong số đó. Tương tự, module json cũng không thể tự serialize hay deserialize các kiểu dữ liệu do bạn tự định nghĩa (user-defined types), vì nó không có thông tin gì về các kiểu dữ liệu này. Nếu bạn xử lý như bình thường, sẽ có lỗi xảy ra
  • Với những kiểu dữ liệu này, bạn cần giúp đỡ python bằng cách cung cấp thêm cho nó các hàm trợ giúp: default cho serialize và object_hook cho deserialize.

Ví dụ: serialize kiểu dữ liệu complex