From the following json, in python, I'd like to extract the value "TEXT". All the keys are constant except for unknown. Unknown could be any string like "a6784t66" or "hobvp*nfe". The value of unknown is not known, only that it will be in that position in each json response.
{
"A": {
"B": {
"unknown": {
"1": "F",
"maindata": [
{
"Info": "TEXT"
}
]
}
}
}
}
one line json
'{"A":{"B":{"unknown":{"1":"F","maindata":[{"Info":"TEXT"}]}}}}'
How would you get the value of "Text"? (I know how to load the json with json.loads)..but I'm not sure how to get the value of "Text". Thanks.
(I'm not sure what the best title is.)
You can use a recursive function to dig through every layer and print its value with an indent
As you said that unknown was at a fixed place You can do the following
This should do the job, since only the unknown key is really 'unknown'
It is a bit lenghty, but in that example above:
You basically treat it as a dictionary, passing the keys to get the values of each nested dictionary. The only different part is when you hit
maindata
, where the resulting value is a list. In order to handle that, we pull the first element[0]
and then access theInfo
key to get the valueTEXT
.In the case of
unknown
changing, you would replace it with a variable that represents the 'known' name it will take at that point in your code:And if I would have actually read your question properly the first time, if you don't know what
unknown
is at any point, you can do something like this:Where
values()
is a variable containing:A single-item list that can be accessed with
[0]
and then you can proceed as above. Note that this is dependent on there only being one item present in that dictionary - you would need to adjust a bit if there were more.