我在从json API中提取数据时遇到了问题。我在试着用"Total_allele_count“我可以从API中提取其他数据,但是当涉及到"exac“数据时,它就不起作用了。
"alterations" : [
{
"Gene_position" : "3164,,,",
"exac" : {
"close_matches" : [],
"exact_matches" : [
{
"exac_allele" : [
{
"West_allele_count" : 0,
"Total_allele_count" : "52413,1",
"Male_allele_count" : "11142,0"这就是它失败的地方。我是不是看多了?
row = alter(data, 'exac', 'Total_allele_count', row)我的方法
def alter(source, org, allele, fileRow):
try:
toAppend = [int(x) for x in source['alterations'][0][org]['exact_matches'][0][allele].split('/')]
#fileRow.append(str(len(toAppend)))
fileRow.append(toAppend[1]/sum(toAppend))
except:
fileRow.append('N/A')
return fileRow 发布于 2017-03-16 02:28:37
诀窍是编写一个执行错误报告的查找函数,这样您就知道您没有错过一个级别。类似于:
def lookup(json, *path):
if not path:
return json
first = path[0]
rest = path[1:]
try:
sub_json = json[first]
except (TypeError, LookupError) as e:
raise ValueError("Failed to look up %r in %s" % (first, json))
return lookup(sub_json, *rest)然后,您可以将alter实现为:
def alter(source, org, allele, fileRow):
value = lookup(source, 'alterations', 0, org, 'exact_matches', 0, allele)
try:
toAppend = value.split('/')
fileRow.append(toAppend[1]/sum(toAppend))
except:
fileRow.append('N/A')
return fileRow 以上内容,并关闭您的数据:
data = { "alterations" : [
{
"Gene_position" : "3164,,,",
"exac" : {
"close_matches" : [],
"exact_matches" : [
{
"exac_allele" : [
{
"West_allele_count" : 0,
"Total_allele_count" : "52413,1",
"Male_allele_count" : "11142,0"
}]}]}}]}我们可以调用alter
alter(data, 'exac', 'Total_allele_count', '')并获取以下回溯:
Traceback (most recent call last):
File "<stdin>", line 35, in <module>
File "<stdin>", line 32, in alter
File "<stdin>", line 27, in lookup
File "<stdin>", line 27, in lookup
File "<stdin>", line 27, in lookup
File "<stdin>", line 27, in lookup
File "<stdin>", line 27, in lookup
File "<stdin>", line 26, in lookup
ValueError: Failed to look up 'Total_allele_count' in {'exac_allele': [{'Total_allele_count': '52413,1', 'Male_allele_count': '11142,0', 'West_allele_count': 0}]}这告诉我们
lookup(source, 'alterations', 0, org, 'exact_matches', 0, allele)缺少一个级别,在最后一个级别之前,它应该是:
lookup(source, 'alterations', 0, org, 'exact_matches', 0, 'exac_allele', allele)运行该命令,我们会得到以下异常:
ValueError: Failed to look up 'Total_allele_count' in [{'Total_allele_count': '52413,1', 'Male_allele_count': '11142,0', 'West_allele_count': 0}]如果仔细观察,值是一个列表,键是一个字符串,所以最终的解决方案是:
lookup(source, 'alterations', 0, org, 'exact_matches', 0, 'exac_allele', 0, allele)发布于 2017-03-16 02:17:48
这样如何:
toAppend = [int(x) for x in source['alterations'][0][org]['exact_matches'][0]['exac_allele'][0][allele].split('/')]
(我猜这只是一个直接的缺陷/错误,并不是真的误解了json结构)
您还应该删除空的,除非(在注释中@thebjorn elludes to ),因为它可能掩盖了这个错误(可能还有其他错误)。
https://stackoverflow.com/questions/42817559
复制相似问题