简体   繁体   English

从 python 2.7 中的嵌套 json(来自 json 响应)中提取字段

[英]Extract fields from nested json (from json response) in python 2.7

I am extracting information from an API.我正在从 API 中提取信息。 I am unable to extract the nested fields from the json response.我无法从 json 响应中提取嵌套字段。 Below is the code and JSON response I am getting from the API.下面是我从 API 得到的代码和 JSON 响应。

url = www.jkhdöfhpirnl.com/api/v2/articleinfo?
token = api_token=ABCDEG7829848bjbmbsjhgd
x = &pmid
id = "123456"
response_suggestions = requests.get(url + token + x + id)
print (response_suggestions.json()['genes'])
[{'symbol': 'MTHFR', 'mentions': 2, 'variants': [{'key': 'E433A', 'matched': ['A1298C'], 'mentions': 3, 'cdna_effects': [{'hgvsc': 'NM_005957.4:c.1298A>C', 'rsid': ''}, {'hgvsc': 'NM_005957.1:c.1298A>C', 'rsid': ''}, {'hgvsc': 'NM_005957.2:c.1298A>C', 'rsid': ''}, {'hgvsc': 'NM_005957.3:c.1298A>C', 'rsid': ''}], 'url': 'https://mastermind.genomenon.com/detail?gene=mthfr&mutation=mthfr:E433A'}], 'url': 'https://mastermind.genomenon.com/detail?gene=mthfr'}]

I would like to extract value of symbol, mentions, and few fields of variants.我想提取符号、提及和几个变量字段的值。 For eg.例如。

'symbol': 'MTHFR', 'mentions': 2, 'variants': [{'key': 'E433A', 'matched': ['A1298C'], 'mentions': 3

How can I do this?我怎样才能做到这一点? Any help is highly appreciated.非常感谢任何帮助。

Make sure you look closely at the structure of the response to find out at which level the different values are and how you can get there.确保您仔细查看响应的结构,以了解不同值在哪个级别以及如何到达那里。

The first step is a list in which everything is enclosed [... ] .第一步是一个列表,其中包含所有内容[... ] Since it has only one element, you can either do [content] = response or content = response[0] which will have the same effect.由于它只有一个元素,因此您可以执行[content] = responsecontent = response[0] ,这将具有相同的效果。

Now you have a dictionary you can work with.现在您有了可以使用的字典。 If you don't know how, look at some guides/ documentation .如果您不知道如何操作,请查看一些指南/ 文档 You usually don't extract parts of a dictionary anyways, but only retrieve the values you need.无论如何,您通常不会提取字典的某些部分,而只会检索您需要的值。 Here some examples to get started这里有一些开始的例子

symbol_value = content['symbol']
first_variant_key = content['variants'][0]['key']
list_of_cdna_effects = content['variants'][0]['cdna_effects']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM