# i want to read 'jsondict' json below store it in cond,field,operator,val variable using recursion(mandatory) but my function returning None, what should i do.
''' jsondict = { "condition": "AND", "rules": [ { "id": "price", "field": "price", "type": "double", "input": "number ", "運算子": "less", "值": 10.25 }, { "條件": "OR", "規則": [ { "id": "category", "field": "category", "type “:“整數”,“輸入”:“選擇”,“運算子”:“相等”,“值”:2},{“id”:“類別”,“欄位”:“類別”,“型別”: “整數”、“輸入”:“選擇”、“運算子”:“等于”、“值”:1 } ] } ] }
cond = []
field = []
operator = []
val = []
def rules(n):
for key, value in n.items():
#print(key, value)
if key == 'condition':
cond.append(value)
elif key == 'rules':
#print(key, values)
for i in value:
#print(i)
for a, b in i.items():
#print(a,b)
if a == 'field':
field.append(b)
#print(b)
elif a == 'operator':
operator.append(b)
elif a == 'value':
val.append(b)
elif a == 'condition':
cond.append(b)
elif a == 'rules':
for j in b:
print(rules(j))
return rules(j) # HERE CALLING FUNTION
rules(jsondict)
print(field) # CHECKING IF VALUES GOING IN VARIABLES
print(operator)
print(val)
print(cond)
'''
uj5u.com熱心網友回復:
- 在遞回的第二步中,您將您的規則方法應用于這種字典:
{ “id”:“類別”,“欄位”:“類別”,“型別”:“整數”,
“輸入”:“選擇”,“運算子”:“等于”,“值”:2 }
它不起作用,因為沒有“規則”鍵。
- 此外,回傳函式會導致 for 回圈中斷。呼叫不帶“return”關鍵字的方法。
嘗試這樣的事情:
def rules(n):
for key, value in n.items():
if key == 'condition':
cond.append(value)
elif key =='field':
field.append(value)
elif key == 'operator':
operator.append(value)
elif key == 'value':
val.append(value)
elif key == 'rules':
for v in value:
rules(v)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/475126.html
