'''
递归遍历json
'''
def parseJson(obj, newObj):
for k in obj:
# 为list的时候
if isinstance(obj, list):
if isinstance(k, list):
if isinstance(newObj, list):
newObj.append(parseJson(k, list()))
elif isinstance(newObj, dict):
newObj[k] = parseJson(k, list())
elif isinstance(k, dict):
if isinstance(newObj, list):
newObj.append(parseJson(k, dict()))
elif isinstance(newObj, dict):
newObj[k] = parseJson(k, dict())
else:
# 这一段 判断key
if isinstance(newObj, list):
newObj.append(k)
elif isinstance(newObj, dict):
newObj[k] = k
# 为dict的时候
elif isinstance(obj, dict):
if isinstance(obj[k], list):
if isinstance(newObj, list):
newObj.append(parseJson(obj[k], list()))
elif isinstance(newObj, dict):
newObj[k] = parseJson(obj[k], list())
elif isinstance(obj[k], dict):
if isinstance(newObj, list):
newObj.append(parseJson(obj[k], dict()))
elif isinstance(newObj, dict):
newObj[k] = parseJson(obj[k], dict())
else:
# 这一段 判断key
if isinstance(newObj, list):
newObj.append(obj[k])
elif isinstance(newObj, dict):
newObj[k] = obj[k]
return newObj
obj = {
"a": 1,
"b": {
"c": 2,
"d": 3,
"e": 4,
"f": [5, 6, {"g": 7, "h": 8}]
}
}
newObj = dict()
parseJson(obj, newObj)
print(f"newObj --> {newObj}")