2017-03-28 7 views
1

지금은 for 루프를 사용하여 키 값 == 변수인지 여부를 하나씩 살펴 봅니다.모든 JSON 하위를 반복합니다.

첫 번째 두 자녀를 얻으려면 [0][1] 색인을 선택하여 하나씩이 작업을 수행합니다. 최대 4 명의 자녀가있을 수 있습니다. elif보다 효율적인 방법이 있습니까?

# INITIALIZE NEW FILTERED DICTIONARY (RETAINING TOP LEVEL ITEMS) 
    newdata = OrderedDict({k:v for k,v in data.items() if k in ['stop_id', 'stop_name']}) 
    newdata['mode'] = [] 
    arrivalarray = [] 

    # ITERATE CONDITIONALLY KEEPING NEEDED SECTIONS 
    for i in data['mode']: 
     if i['route'][0]['route_name'] == line: 
      if i['route'][0]['direction'][0]['direction_name'] == direction: 
       for s in i['route'][0]['direction'][0]['trip']: 
        arrivalarray.append(s['pre_away']) 
      elif i['route'][0]['direction'][1]['direction_name'] == direction: 
       for s in i['route'][0]['direction'][1]['trip']: 
        arrivalarray.append(s['pre_away']) 

답변

0

JSON 데이터를로드하면 더 이상 JSON 데이터가 아닙니다. 이것은 파이썬리스트, 딕셔츠, 문자열 등 중첩 된 일련의 것입니다. 따라서 for 루프를 사용하여 목록의 요소를 반복하는 등 모든 파이썬 데이터 구조에 대해 할 수있는 것을 할 수 있습니다 :

for d in i['route'][0]['direction']: 
    if d['direction_name'] == direction: 
     for s in d['trip']: 
      arrivalarray.append(s['pre_away']) 
0

그래, 반복 대신 재귀를 사용할 수 있으며 실제로는 DFS입니다.

def traverse_json(json, depth): 
    if depth = 0 : 
     return []; 
    else: 
     data = []; 
     for i in json.keys(): 
      if isinstance(json[i], dict): 
        data += traverse_json(json[i], depth -1) 
      else : 
        data.append(json[i]) 
     return data 

필요한 최대 깊이로 시작할 수 있습니다.