# 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", "operator": "less", "value": 10.25 }, { "condition": "OR", "rules": [ { "id": "category", "field": "category", "type": "integer", "input": "select", "operator": "equal", "value": 2 }, { "id": "category", "field": "category", "type": "integer", "input": "select", "operator": "equal", "value": 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)
'''
CodePudding user response:
- In the 2nd step of recursion, you apply your rules method to this kind of dicts:
{ "id": "category", "field": "category", "type": "integer",
"input": "select", "operator": "equal", "value": 2 }
It does not work because there is no "rules" key.
- Moreover, returning the function causes a break of for loop. Call the method without the "return" keyword.
Try something like this:
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)