You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I don't know if I'm abusing the intended purpose of this project, but I created a function that recursively looks for a given key inside a JSON. The original code follows:
def key_exists(obj, key):
stack = [obj]
while stack:
current = stack.pop()
if isinstance(current, dict):
if key in current:
return True
stack.extend(current.values())
elif isinstance(current, list):
stack.extend(current)
return False
I tested it as a standalone function, and it worked like a charm.
However, I tested it as an embedded function in the context, and it didn't work. After some peeks and pokes, I discovered the JSON was transformed, it changed the dicts into OrderedDicts and lists into tuples. After some changes, the following code worked:
def key_exists(obj, key):
stack = [obj]
while stack:
current = stack.pop()
if isinstance(current, tuple):
current = list(current)
if isinstance(current, dict) or isinstance(current, OrderedDict):
if key in current:
return True
stack.extend(list(current.values()))
elif isinstance(current, list):
stack.extend(current)
return False
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Good morning!
I don't know if I'm abusing the intended purpose of this project, but I created a function that recursively looks for a given key inside a JSON. The original code follows:
I tested it as a standalone function, and it worked like a charm.
However, I tested it as an embedded function in the context, and it didn't work. After some peeks and pokes, I discovered the JSON was transformed, it changed the dicts into OrderedDicts and lists into tuples. After some changes, the following code worked:
My question is, why exactly did it happen?
Thank you for the clarification!
Beta Was this translation helpful? Give feedback.
All reactions