JavaScript
2
1
# 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.
2
”’ 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 } ] } ] }
JavaScript
37
1
cond = []
2
field = []
3
operator = []
4
val = []
5
6
def rules(n):
7
for key, value in n.items():
8
#print(key, value)
9
if key == 'condition':
10
cond.append(value)
11
12
elif key == 'rules':
13
#print(key, values)
14
for i in value:
15
#print(i)
16
for a, b in i.items():
17
#print(a,b)
18
if a == 'field':
19
field.append(b)
20
#print(b)
21
elif a == 'operator':
22
operator.append(b)
23
elif a == 'value':
24
val.append(b)
25
elif a == 'condition':
26
cond.append(b)
27
elif a == 'rules':
28
for j in b:
29
print(rules(j))
30
return rules(j) # HERE CALLING FUNTION
31
rules(jsondict)
32
33
print(field) # CHECKING IF VALUES GOING IN VARIABLES
34
print(operator)
35
print(val)
36
print(cond)
37
”’
Advertisement
Answer
- 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:
JavaScript
14
1
def rules(n):
2
for key, value in n.items():
3
if key == 'condition':
4
cond.append(value)
5
elif key =='field':
6
field.append(value)
7
elif key == 'operator':
8
operator.append(value)
9
elif key == 'value':
10
val.append(value)
11
elif key == 'rules':
12
for v in value:
13
rules(v)
14