2017-03-15 1 views
1

json API에서 데이터를 가져 오는 데 문제가 있습니다. "Total_allele_count"를 얻으려고합니다. 나는 API에서 다른 데이터를 가져올 수 있지만 "엑서사"데이터의 경우 작동하지 않습니다.json API 데이터 추출

"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  
+0

귀하의 JSON이 완전하지 않습니다. –

+1

"작동하지 않음"은 분석을 제공 할만큼 충분히 정의되지 않았습니다. "여기가 실패한 곳입니다."라고 말할 때, 정말입니까? 어떻게 알았어? 나는 '무엇을 잘못 발견했는지 알아내는 데 사용할 수있는 흥미로운 추적 표시를 숨기고 있습니다. – thebjorn

답변

0

트릭은 오류보고를 수행하는 조회 기능을 작성하여 수준을 놓치지 않았 음을 알 수 있습니다. 뭔가 같은 :

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 같이

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를 호출 할 수 있습니다 :

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  
위와

및 데이터를 폐쇄

alter(data, 'exac', 'Total_allele_count', '') 

다음과 같은 역 추적 얻을 :

lookup(source, 'alterations', 0, org, 'exact_matches', 0, allele) 

이 마지막 전에 레벨을 누락하고해야한다고 우리에게 알려줍니다

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, '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}] 
주의 깊게 보면 691,363,210

, 값은 목록이며, 최종 솔루션은 다음 그래서 키는 문자열입니다

lookup(source, 'alterations', 0, org, 'exact_matches', 0, 'exac_allele', 0, allele) 
0

방법에 관하여 :

toAppend = [int(x) for x in source['alterations'][0][org]['exact_matches'][0]['exac_allele'][0][allele].split('/')]

(내가 추측하고있어이 그냥 직선 결함/버그까지 정말 json으로 구조를 오해하지 않음)

당신은 또한 (a @thebjorn은이 오류 (그리고 아마도 다른 것들)를 가릴 가능성이 있기 때문에 주석에서 언급하고 있습니다.