I need to read a JSON message that has a key called “derivedFrom”. Its value might have either this form:
Case 1. "derivedFrom": "id1"
or this:
Case 2. "derivedFrom": ["id1", "id2", "id3"]
What I need to do is something very basic: read the value(s) and loop over them. Right now I am doing this:
#line contains JSON string
data = json.loads(line)
# ...
derivedIds = data['derivedFrom']
for deid in derivedIds:
# ...
This works fine for Case 2 but for Case 1 it loops over individual characters of the id “id1” which is clearly not what I need.
How do I modify the block above to handle both cases correctly? Thx
If you know that derivedFrom’s value will always be a list or a value (that is, not a dict):
The fact that it’s coming from JSON simplifies matters as it greatly restricts the number of datatypes you have to worry about.