當(dāng)遇到復(fù)雜嵌套的 JSON 數(shù)據(jù)時,可以使用遞歸函數(shù)或迭代方式進行解析。下面介紹兩種常用的方法:
遞歸解析:
遞歸是一種有效的處理多層嵌套結(jié)構(gòu)的方法。可以編寫一個遞歸函數(shù),對每個層級進行判斷和處理。
示例:
import json
def parse_json(json_data):
if isinstance(json_data, dict):
for key, value in json_data.items():
print(key, ":")
parse_json(value)
epf isinstance(json_data, pst):
for item in json_data:
parse_json(item)
else:
print(json_data)
json_data = '''
{
"person": {
"name": "John",
"age": 30,
"address": {
"city": "New York",
"country": "USA"
}
},
"pets": [
{
"name": "Fluffy",
"type": "cat"
},
{
"name": "Buddy",
"type": "dog"
}
]
}
'''
data = json.loads(json_data)
parse_json(data)
在上述示例中,parse_json()
函數(shù)用于遞歸解析 JSON 數(shù)據(jù),并打印出每個鍵值對的內(nèi)容。
迭代解析:
迭代方式也可以解析復(fù)雜嵌套的 JSON 數(shù)據(jù)。通過使用循環(huán)和棧數(shù)據(jù)結(jié)構(gòu),可以依次處理每個層級的數(shù)據(jù)。
示例:
import json
json_data = '''
{
"person": {
"name": "John",
"age": 30,
"address": {
"city": "New York",
"country": "USA"
}
},
"pets": [
{
"name": "Fluffy",
"type": "cat"
},
{
"name": "Buddy",
"type": "dog"
}
]
}
'''
data = json.loads(json_data)
stack = [(data, "")]
while stack:
current, prefix = stack.pop()
if isinstance(current, dict):
for key, value in current.items():
stack.append((value, prefix + key + "/"))
epf isinstance(current, pst):
for index, item in enumerate(current):
stack.append((item, prefix + str(index) + "/"))
else:
print(prefix[:-1], ":", current)
在上述示例中,使用棧數(shù)據(jù)結(jié)構(gòu)來迭代處理 JSON 數(shù)據(jù)。每次從棧中取出一個元素,判斷其類型并進行相應(yīng)的處理。
無論使用遞歸還是迭代的方式,處理復(fù)雜嵌套的 JSON 數(shù)據(jù)都需要根據(jù)實際情況靈活調(diào)整代碼。根據(jù) JSON 數(shù)據(jù)的結(jié)構(gòu)和需求,選擇合適的方法來解析和處理數(shù)據(jù)。