Computer >> Máy Tính >  >> Lập trình >> Python

Python - Các cách chuyển đổi chuỗi thành đối tượng json

Gửi và nhận dữ liệu nói chung trong một chuỗi biểu mẫu từ điển (đối tượng JSON) trong nhiều API web để sử dụng dữ liệu đó để trích xuất thông tin có ý nghĩa, chúng tôi cần chuyển đổi dữ liệu đó ở dạng từ điển và sử dụng cho các hoạt động tiếp theo.

Ví dụ

# converting string to json
# using json.loads
import json
# inititialising json object
ini_string = {'vishesh': 1, 'ram' : 5, 'prashant' : 10, 'vishal' : 15}
# printing initial json
ini_string = json.dumps(ini_string)
print ("initial 1st dictionary", ini_string)
print ("type of ini_object", type(ini_string))
# converting string to json
final_dictionary = json.loads(ini_string)
# printing final result
print ("final dictionary", str(final_dictionary))
print ("type of final_dictionary", type(final_dictionary))

Đầu ra

('initial 1st dictionary', '{"vishal": 15, "ram": 5, "vishesh": 1, "prashant": 10}')
('type of ini_object', <type 'str'>)
('final dictionary', "{u'vishal': 15, u'ram': 5, u'vishesh': 1, u'prashant': 10}")
('type of final_dictionary', <type 'dict'>)