码迷,mamicode.com
首页 > 编程语言 > 详细

Python解析json字符串

时间:2014-10-29 02:14:42      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:http   os   ar   for   sp   on   2014   问题   bs   

问题分析

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

bubuko.com,布布扣

源码

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字符串

标签:http   os   ar   for   sp   on   2014   问题   bs   

原文地址:http://my.oschina.net/crazyharry/blog/338350

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!