2010-11-23 12 views
8

simplejson과 함께 Python을 사용하여 여러 개의 중첩 된 사전을 JSON에 직렬화합니다.JSON 직렬화에서 빈 값/null 값 제외

빈/null 값을 자동으로 제외 할 수있는 방법이 있습니까?

예를 들어,이 직렬화 :

{ 
    "dict1" : { 
    "key1" : "value1", 
    "key2" : None 
    } 
} 

{ 
    "dict1" : { 
    "key1" : "value1" 
    } 
} 

에이 작업을 수행 할 수 Inclusion.NON_NULL를 사용할 수있는 자바 잭슨을 사용하는 경우. 거기 simplejson 동등한가 있습니까?

답변

11
def del_none(d): 
    """ 
    Delete keys with the value ``None`` in a dictionary, recursively. 

    This alters the input so you may wish to ``copy`` the dict first. 
    """ 
    # For Python 3, write `list(d.items())`; `d.items()` won’t work 
    # For Python 2, write `d.items()`; `d.iteritems()` won’t work 
    for key, value in list(d.items()): 
     if value is None: 
      del d[key] 
     elif isinstance(value, dict): 
      del_none(value) 
    return d # For convenience 

샘플 사용 :

>>> mydict = {'dict1': {'key1': 'value1', 'key2': None}} 
>>> print(del_none(mydict.copy())) 
{'dict1': {'key1': 'value1'}} 

는 그런 다음 json 해당 급지 할 수 있습니다.

+0

Em .... 그 결과'RuntimeError : Python 3.5에서 반복 도중 크기가 변경된 사전 '이 생성되었습니다. –

+0

''''''''값을 가진 키를 삭제합니다. 사전, 재귀. 이 입력을 변경하지 않지만, 복사 사전. 아동 사전도 복사됩니다. 다른 객체가 복사되지 않습니다. 을 "" "키 REZ = d.copy() , D의 값을 .items() : 값이 None 또는 value == ''인 경우 : del rez [key] elif isinstance (value, dict) : rez [key] = del_none (값) return z'' –

+1

@AleksandrPanzin : Python 3을 대상으로하는 코드를 Python 2 용으로 업데이트했습니다.이 기능은 7 년 전에 작성되었습니다. 그러나 제자리에서의 수정으로 남겨 두었습니다. –

0
def excludeNone(d): 
    for k in list(d): 
     if k in d: 
      if type(d[k]) == dict: 
       excludeNone(d[k]) 
      if not d[k]: 
       del d[k] 
+4

만약 d [k]가'd [k]'가 아니라면'd [k]가 아닌 '을 사용하는 것이 더 안전 할 것입니다. 그렇지 않으면 빈 문자열과 0 값 또한 출력에서 ​​제외됩니다. –

6
>>> def cleandict(d): 
...  if not isinstance(d, dict): 
...   return d 
...  return dict((k,cleandict(v)) for k,v in d.iteritems() if v is not None) 
... 
>>> mydict = dict(dict1=dict(key1='value1', key2=None)) 
>>> print cleandict(mydict) 
{'dict1': {'key1': 'value1'}} 
>>> 

나는 기존의 사전은 생성 방식에 따라 미묘한 영향을 미칠 수 변경, 일반적으로 del를 사용하여 좋아하지 않는다. None으로 새 사전을 만들면 모든 부작용을 예방할 수 있습니다.