首页 > 代码库 > Python解析json字符串

Python解析json字符串

问题分析

解析一个json字符串并将其所以key和value提取出来置于list当众,首先不得不对json的格式进行分析,以下则是个人的一个分析过程:

源码

def read(obj,key):
    collect = list()
    for k in obj:
        v = obj[k]

        if isinstance(v,str) or isinstance(v,unicode):
            if key==‘‘:
                collect.append({k:v})
            else:
                collect.append({str(key)+"."+k:v})
        elif isinstance(v,int):
            if key==‘‘:
                collect.append({k:v})
            else:
                collect.append({str(key)+"."+k:v})
        elif isinstance(v,bool):
            if key==‘‘:
                collect.append({k:v})
            else:
                collect.append({str(key)+"."+k:v})
        elif isinstance(v,dict):
            collect.extend(read(v,k))
        elif isinstance(v,list):
            collect.extend(readList(v,key))
    return collect
    
def readList(obj,key):
    collect = list()
    for index,item in enumerate(obj):
        for k in item:
            v = item[k]
            if isinstance(v,str) or isinstance(v,unicode):
                collect.append({key+"["+str(index)+"]"+"."+k:v})
            elif isinstance(v,int):
                collect.append({key+"["+str(index)+"]"+"."+k:v})
            elif isinstance(v,bool):
                collect.append({key+"["+str(index)+"]"+"."+k:v})
            elif isinstance(v,dict):
                collect.extend(read(v,key+"["+str(index)+"]"))
            elif isinstance(v,list):
                collect.extend(readList(v,key+"["+str(index)+"]"))
    return collect

示例

import json

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}]


Python解析json字符串