在python中找到嵌套的json字典中的值 [英] Find a value within nested json dictionary in python
问题描述
从下面的json,在python中,我想提取值TEXT。除了未知之外,所有键都是常数。未知可能是任何字符串,如a6784t66或hobvp * nfe。 未知的值不知道,只有在每个json响应中才会处于该位置。
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"
}
]
}
}
}
}
一行json
'{"A":{"B":{"unknown":{"1":"F","maindata":[{"Info":"TEXT"}]}}}}'
如何获取文本的值? (我知道如何加载json与json.loads)..但我不知道如何获取文本的值。谢谢。
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.)
推荐答案
有点长,但在上面的例子中:
It is a bit lenghty, but in that example above:
In [1]: import json
In [2]: s = """\
...: {
...: "A": {
...: "B": {
...: "unknown": {
...: "1": "F",
...: "maindata": [
...: {
...: "Info": "TEXT"
...: }
...: ]
...: }
...: }
...: }
...: }"""
In [3]: data = json.loads(s)
In [4]: data['A']['B']['unknown']['maindata'][0]['Info']
Out[4]: u'TEXT'
您基本上将其视为字典,传递键以获取每个嵌套字典的值。唯一不同的部分是当您点击 maindata
,其中生成的值是列表。为了处理这个问题,我们拉第一个元素 [0]
,然后访问信息
键以获取值 TEXT
。
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 the Info
key to get the value TEXT
.
在未知
更改的情况下,你将用一个变量来替换它,代表代码中的那个已知名称:
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:
my_variable = 'some_name'
data['A']['B'][my_variable]['maindata'][0]['Info']
如果我第一次真正读过你的问题,如果你不知道什么未知
在任何一点,你可以这样做:
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:
data['A']['B'].values()[0]['maindata'][0]['Info']
其中 values()
是一个变量,包含:
Where values()
is a variable containing:
[{u'1': u'F', u'maindata': [{u'Info': u'TEXT'}]}]
可以是一个单项列表使用 [0]
获取,然后可以如上进行。请注意,这取决于该字典中只有一个项目 - 如果有更多,您需要调整一点。
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.
这篇关于在python中找到嵌套的json字典中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!