在python中读取并处理多个json文件

时间:2018-03-15 05:22:52

标签: python json django

我正在尝试使用用户输入处理许多json文件。 如果GeneListA中有三个缩进数据[“a”,“a”,“a”],我想它将运行代码三次 jsonurl =“http://abc.def/a/format=json

然而,我收到了错误:

Traceback (most recent call last):
  File "/Users/me/miniconda3/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Users/me/miniconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/me/miniconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/me/Desktop/Project/gsea/analysis/views.py", line 49, in result
    for gene in data[0][gidA]:
KeyError: 'NC_000913\r\nNC_000913\r\nNC_000913'

这是我的代码:

AGOAnnos = []
for genefromlist in GeneListA:
    jsonurl = "http://abc.def/"+genefromlist+"/format=json"
    print(jsonurl)

    with urllib.request.urlopen(jsonurl) as url:
        data = json.loads(url.read().decode())

    for gene in data[0][gidA]:
        for anno in data[0][gidA][gene]:

            if type(anno) is dict:
                GOAnno = re.search(r'GO:\d+',anno["ID"])
                if GOAnno:
                    AGOAnnos.append(GOAnno.group())

            elif type(anno) is str:
                GOAnno = re.search(r'GO:\d+',anno)
                if GOAnno:
                    AGOAnnos.append(GOAnno.group())

1 个答案:

答案 0 :(得分:0)

我无法在代码中找到变量(gidA / gene)的值。 引发错误的原因是数据响应中没有gidA的密钥