废话不多说。。。这个循环递归真是折磨了我两天。。。
上代码解析一个四层json
# -*- coding:utf-8 -*-
'''
Created on 2019
@author: pt0521
'''
import re
import json as js
import sys
def get_json_nums_of_layers(file_path):
fo=open(file_path,'r',encoding='utf-8')
jsonstr = fo.read()#将json作为整个的字符串读取进去
pos1=list()#用于存放
for m in re.finditer('{', jsonstr):
pos1.append(m.start())
print(pos1)
pos2=jsonstr.find('}')
print(pos2)
for i in range(len(pos1)):
if pos1[i]>pos2:
return i
else:
return len(pos1)
fo.close()
def get_json(file_path,nums_layer_toget):
obj={}
num=1
if(nums_layer_toget>get_json_nums_of_layers(file_path)):
print("所要解析的层数超过该json拥有的层数!请修正")
else:
fo=open(file_path,'r',encoding='utf-8')
jsonstr = fo.read()
jsonstr=js.loads(jsonstr)
get_json_operation(jsonstr, nums_layer_toget,obj)
def get_json_operation(jsonstr,nums_layer_toget,obj):
while(nums_layer_toget>=0):
if nums_layer_toget==0:
return nums_layer_toget+1
else:
m=list(jsonstr.keys())
print('这一层的键有',m)
for key in jsonstr:
# print(key)
if isinstance(jsonstr[key], list) and nums_layer_toget>=1:
print('该层列表有',len(jsonstr[key]),'个元素')
j=0
cd=len(jsonstr[key])
temp_json=jsonstr[key]
if j<=cd-1:
jsonstr=jsonstr[key][j]
# print(jsonstr)
get_json_operation(jsonstr, nums_layer_toget-1,obj)
j=j+1
if j==cd:
return nums_layer_toget+1
else:
while(j