[转]解析多级json数据为list中嵌套一级字典的形式
#!/usr/bin/env python
# encoding: utf-8
import json
def read(obj,key):
collect = list()
for k in obj:
v = obj[k]
if isinstance(v,dict):
collect.extend(read(v,k))
elif isinstance(v,list):
if key=='':
collect.extend(readList(v,k))
else:
collect.extend(readList(v,key+"."+k))
else:
if key=='':
collect.append({k:v})
else:
collect.append({str(key)+"."+k:v})
return collect
def readList(obj,key):
collect = list()
for index,item in enumerate(obj):
for k in item:
v = item[k]
if isinstance(v,dict):
collect.extend(read(v,key+"["+str(index)+"]"))
elif isinstance(v,list):
collect.extend(readList(v,key+"["+str(index)+"]"))
else:
collect.append({key+"["+str(index)+"]"+"."+k:v})
return collect
jsonStr = '{"num":1,"boo":true,"obj":{"sex":"boy","age":20},"result":[{"name":"saas","leverl":[{"name":"english","mark":99}],"id":"336efba7-259d-4057-ae1e-679e81419cd7","module":"life"}]}'
ojt = json.loads(jsonStr)
print read(ojt,'')
输出结果
[{u'num': 1}, {u'obj.age': 20}, {u'obj.sex': u'boy'}, {u'[0].module': u'life'}, {u'[0].name': u'saas'}, {u'[0][0].name': u'english'}, {u'[0][0].mark': 99}, {u'[0].id': u'336efba7-259d-4057-ae1e-679e81419cd7'}, {u'boo': True}]