SWE Thật vậy. Thực tập sinh SWE @linuxfoundation '20. Chuyên môn vững vàng về mã nguồn mở, cấu trúc dữ liệu và lập trình
Làm việc với dữ liệu JSON trong PythonXuất bản ngày 05 tháng 5 năm 2020
Làm cách nào để phân tích dữ liệu Nested Json trong Python?
Nếu bạn đang làm việc với Json, hãy đưa mô-đun json vào mã của bạn
import json
Chuyển đổi các đối tượng Python thành chuỗi Json trong Python. Và sau đó từ chuỗi Json sang Từ điển Json
import json
# a Python object [dict]:
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON string:
y = json.dumps[x]
# convert json string to Json Dict
jsonDict = json.loads[y]
Bây giờ để truy cập bất kỳ khóa Json nào
import json
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON string:
y = json.dumps[x]
# convert json string to Json Dict
jsonDict = json.loads[y]
print [jsonDict['name']]
print [jsonDict['age']]
Viết dữ liệu json trong tệp
import json
data = {
'bill': 'tech',
'federer': 'tennis',
'ronaldo': 'football',
'people' : [ {
'name': 'Scott',
'website': 'stackabuse.com',
'from': 'Nebraska'},
{'name': 'Larry',
'website': 'google.com',
'from': 'Michigan' } ]
}
with open['data.txt', 'w'] as outfile:
json.dump[data, outfile]
Đọc dữ liệu từ tệp Json [Chúng tôi sẽ đọc cùng một tệp dữ liệu mà chúng tôi kết xuất dữ liệu ở trên]
import json
with open['data.txt'] as json_file:
data = json.load[json_file]
print ["bill:", data['bill']]
print [""]
for person in data['people']:
print["Name:", person['name']]
print["Website:", person['website']]
print["From:", person['from']]
print[""]
Lặp lại qua dữ liệu Json có danh sách, chuỗi json, Json lồng nhau. Ở đây tôi sẽ giải thích cách làm việc với Json phức tạp và trích xuất dữ liệu từ nó
import json
def checkList[ele, prefix]:
for i in range[len[ele]]:
if [isinstance[ele[i], list]]:
checkList[ele[i], prefix+"["+str[i]+"]"]
elif [isinstance[ele[i], str]]:
printField[ele[i], prefix+"["+str[i]+"]"]
else:
checkDict[ele[i], prefix+"["+str[i]+"]"]
def checkDict[jsonObject, prefix]:
for ele in jsonObject:
if [isinstance[jsonObject[ele], dict]]:
checkDict[jsonObject[ele], prefix+"."+ele]
elif [isinstance[jsonObject[ele], list]]:
checkList[jsonObject[ele], prefix+"."+ele]
elif [isinstance[jsonObject[ele], str]]:
printField[jsonObject[ele], prefix+"."+ele]
def printField[ele, prefix]:
print [prefix, ":" , ele]
data = {'field1': 'hello1',
'field2': 'hello2',
'NestedJson': {'Field': 'helloNested1',
'List': [{'f01': 'v01', 'f02': 'v02'},
{'f11': 'v11'}],
'NestedNestedJson': {'Field1': 'value1',
'Field2': 'value2'}
},
'List': [{'a1': 'b1'},
{'a1': 'b1'}],
'ElementList': ['ele1', 'ele2', 'ele3']
}
#Iterating all the fields of the JSON
for element in data:
#If Json Field value is a Nested Json
if [isinstance[data[element], dict]]:
checkDict[data[element], element]
#If Json Field value is a list
elif [isinstance[data[element], list]]:
checkList[data[element], element]
#If Json Field value is a string
elif [isinstance[data[element], str]]:
printField[data[element], element]
Đầu ra của đoạn mã trên là. -
field1 : hello1
field2 : hello2
NestedJson.Field : helloNested1
NestedJson.List[0].f01 : v01
NestedJson.List[0].f02 : v02
NestedJson.List[1].f11 : v11
NestedJson.NestedNestedJson.Field1 : value1
NestedJson.NestedNestedJson.Field2 : value2
List[0].a1 : b1
List[1].a1 : b1
ElementList[0] : ele1
ElementList[1] : ele2
ElementList[2] : ele3
JsonPythonPython 3. xPython 2. 7máy tính xách tay ipython
Bài báo cáo
Thưởng thức bài viết này?
4
Chia sẻ
Simran Singhal
SWE Thật vậy. Thực tập sinh SWE @linuxfoundation '20. Chuyên môn vững vàng về mã nguồn mở, cấu trúc dữ liệu và lập trình
Tôi là Simran Singhal, Kỹ sư phần mềm tại Indeed. com. Tôi rất quan tâm đến Giải quyết vấn đề bằng thuật toán và đã lập trình được khoảng bảy năm nay. Tôi là một người đam mê mã nguồn mở và đóng góp tích cực cho nhiều dự án