2014-10-22 3 views
1

의 수정 난이 같은 JSON 파일이 있습니다재귀 반복 및 DICT

{ 
    "top_key1": { 
       "bottom.key1": "one", 
       "bottom.key2": "two" 
       }, 
    "top_key2": [ 
       "bottom.key1": "one", 
       "bottom.key2": "two", 
       ] 
} 

를 내가 나를 기간 (.)와 키를 저장하도록 허용하지 않습니다 데이터 구조에 저장해야 할에 그것. 이 JSON 구조를 트래버스하면 모든 . 발생을 _으로 바꿀 수 있습니까?

{ 
    "top_key1": { 
       "bottom_key1": "one", 
       "bottom_key2": "two" 
       }, 
    "top_key2": [ 
       "bottom_key1": "one", 
       "bottom_key2": "two", 
       ] 
} 

JSON 파일이 중첩 될 수있는 몇 가지 (알 수없는) 시간도 값에 .이있을 수 있지만, 나는 그들이 _로 대체하지 않으 : 최종 결과가 될 것입니다. 또한 "top_key2"의 값은 보존되어야하는 목록입니다. 너무 열심히

+1

이를 참조하십시오 : 키 - 값 구조 있지만, 목록과 을 처리 할 수있는 별도의 케이스를 추가는 매우 간단하다 http://stackoverflow.com/questions/11188889/how-can-i-edit-rename- keys-during-json-load-in-python –

+1

이것은 a이다. 마침내 나를 도왔습니다. 감사! – licorna

답변

3

하지 내 생각, 단지 현재 값이 다른 DICT인지 확인합니다 isinstance를 사용하여 예를 목록으로,

nested_dict = { 
    "top_key1": { 
       "bottom.key1": "one", 
       "bottom.key2": "two" 
       }, 
    "top_key2": { 
       "bottom.key1": "one", 
       "bottom.key2": "two", 
       } 
} 

def replace_dots(nested_dict): 
    result_dict = {} 
    for key, val in nested_dict.items(): 
     key = key.replace('.', '_') 
     if isinstance(val, dict): 
      result_dict[key] = replace_dots(val) 
     else: 
      result_dict[key] = val 
    return result_dict 

fixed = replace_dots(nested_dict) 

fixed 
Out[4]: 
{'top_key1': {'bottom_key1': 'one', 'bottom_key2': 'two'}, 
'top_key2': {'bottom_key1': 'one', 'bottom_key2': 'two'}} 

내가 완전히 편집을 이해한다면 잘 모르겠어요 여전히이있는

nested_dict2 = { 
    "top_key1": { 
       "bottom.key1": "one", 
       "bottom.key2": "two" 
       }, 
    "top_key2": ["list.item1", "list.item2"] 
} 

def replace_dots(nested_dict): 
    result_dict = {} 
    for key, val in nested_dict.items(): 
     key = key.replace('.', '_') 
     if isinstance(val, dict): 
      result_dict[key] = replace_dots(val) 
     elif isinstance(val, list): 
      cleaned_val = [v.replace('.', '_') for v in val] 
      result_dict[key] = cleaned_val 
     else: 
      result_dict[key] = val 
    return result_dict 

replace_dots(nested_dict2) 
Out[7]: 
{'top_key1': {'bottom_key1': 'one', 'bottom_key2': 'two'}, 
'top_key2': ['list_item1', 'list_item2']} 
+1

마리우스에게 감사드립니다. JSON 객체에는 목록이 있고 마침표가있는 키가 있으므로이 방법에는 해당 사용 사례가 없습니다. – licorna

+0

@licorna : 내 편집을 참조하십시오. 추가 유형 체크를 추가하여 목록을 처리 할 수 ​​있습니다. 질문에있는 예제 목록이 JSON처럼 완전히 이해가되지는 않았지만, 의미. – Marius