json解析任意复杂json(显示层次key与value)

import json

def dict_generator(indict, pre=None):
    pre = pre[:] if pre else []
    if isinstance(indict, dict):
        for key, value in indict.items():
            if isinstance(value, dict):
                if len(value) == 0:
                    yield pre+[key, '{}']
                else:
                    for d in dict_generator(value, pre + [key]):
                        yield d
            elif isinstance(value, list):
                if len(value) == 0:
                    yield pre+[key, '[]']
                else:
                    for v in value:
                        for d in dict_generator(v, pre + [key]):
                            yield d
            elif isinstance(value, tuple):
                if len(value) == 0:
                    yield pre+[key, '()']
                else:
                    for v in value:
                        for d in dict_generator(v, pre + [key]):
                            yield d
            else:
                yield pre + [key, value]
    else:
        yield indict


def get_itemboy1(filepath):
   tmp = []
   file = open(filepath, 'r', encoding='utf-8')
   testread = file.readlines()
   first_line = testread[0]  # 取第一行
   # print(first_line)
   if first_line.startswith(u'\ufeff'):
      mydata = first_line.encode('utf8')[3:].decode('utf8')
   file.close()
   # 将一个python对象编码成json字符串/编码
   testdata = json.dumps(mydata, indent=4, ensure_ascii=False)
   # 将JSON格式的字符串解码成python对象/解码
   testjson = json.loads(testdata)
   print(testjson)
   print(type(testjson))
   bb = json.loads(testjson)
   print(bb)
   print(type(bb))
   sJOSN = testjson
   sValue = json.loads(sJOSN)
   for i in dict_generator(sValue):
      print(''.join(i[0:-1]), ':', i[-1])

   return tmp

if __name__ == "__main__":
    #get_itemboy('C:\\Users\\Administrator\\Desktop\\testgo\\testgo0.txt')
    get_itemboy1('C:\\Users\\31216\\Desktop\\testgo0.txt')
   #C:\Users\31216\Desktop\
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值