Python 如何使用以json对象为输入的列表查找字典的最大深度
我有一个JSON对象,我想编写一个Python程序,将其作为输入并计算其最大深度 代码Python 如何使用以json对象为输入的列表查找字典的最大深度,python,arrays,json,nested-lists,Python,Arrays,Json,Nested Lists,我有一个JSON对象,我想编写一个Python程序,将其作为输入并计算其最大深度 代码 f = open(r"c:\python\8_DEPTH\JSON_Kino.JSON", "r") x = f.read() def depth(x): if type(x) is dict and x: return 1 + max(depth(x[a]) for a in x) if type(x) is list and x:
f = open(r"c:\python\8_DEPTH\JSON_Kino.JSON", "r")
x = f.read()
def depth(x):
if type(x) is dict and x:
return 1 + max(depth(x[a]) for a in x)
if type(x) is list and x:
return 1 + max(depth(a) for a in x)
return 0
print(depth(x))
我的问题是,当我运行程序时,它计数为0。有什么想法吗?试试这个:
def depth(myDict):
str_dic = str(myDict)
counter = 0
for i in str_dic:
if i == "{":
counter += 1
return(counter)
print (depth(myDict))
x
始终是一个字符串,这就是为什么函数总是返回0欢迎使用SO!显示JSON是个好主意。正如Moinuddin所说,您还没有将JSON字符串解析为dict或list,因此函数只返回0,因为这两个分支都不是真的。您是想先使用json.loads(x)
吗?您可以将答案标记为解决方案,但请不要在问题中添加(已解决)。看,这是一个不错的黑客!如果其中一个dicts包含一个带有{
字符的字符串怎么办?谢谢你的回答,但如果字典中还有一个列表,我还想计算深度。