bestsource

JSON 오브젝트의 아이템이 "json.dumps"를 사용하여 고장났습니까?

bestsource 2023. 3. 20. 23:23
반응형

JSON 오브젝트의 아이템이 "json.dumps"를 사용하여 고장났습니까?

사용하고 있다json.dumpsjson으로 변환하다

countries.append({"id":row.id,"name":row.name,"timezone":row.timezone})
print json.dumps(countries)

결과는 다음과 같습니다.

[
   {"timezone": 4, "id": 1, "name": "Mauritius"}, 
   {"timezone": 2, "id": 2, "name": "France"}, 
   {"timezone": 1, "id": 3, "name": "England"}, 
   {"timezone": -4, "id": 4, "name": "USA"}
]

id, name, timezone 순으로 키를 지정하고 싶은데, 대신 timezone, id, name이 표시됩니다.

어떻게 고쳐야 할까요?

Python 둘 다dict(Python 3.7 이전) 및 JSON 개체는 순서가 매겨지지 않은 컬렉션입니다.합격할 수 있다sort_keys키를 정렬하려면 다음 명령을 사용합니다.

>>> import json
>>> json.dumps({'a': 1, 'b': 2})
'{"b": 2, "a": 1}'
>>> json.dumps({'a': 1, 'b': 2}, sort_keys=True)
'{"a": 1, "b": 2}'

특정 주문이 필요한 경우 다음을 사용할 수 있습니다.

>>> from collections import OrderedDict
>>> json.dumps(OrderedDict([("a", 1), ("b", 2)]))
'{"a": 1, "b": 2}'
>>> json.dumps(OrderedDict([("b", 2), ("a", 1)]))
'{"b": 2, "a": 1}'

Python 3.6 이후 키워드 인수 순서는 유지되며 위의 문법은 보다 좋은 구문을 사용하여 다시 쓸 수 있습니다.

>>> json.dumps(OrderedDict(a=1, b=2))
'{"a": 1, "b": 2}'
>>> json.dumps(OrderedDict(b=2, a=1))
'{"b": 2, "a": 1}'

PEP 468 - 키워드 인수 순서 보존을 참조해 주세요.

입력이 JSON으로 되어 있는 경우는, 주문을 보존합니다(취득하기 위해서).OrderedDict합격할 수 있습니다.object_pair_hook@Fred Yankowski의 제안대로:

>>> json.loads('{"a": 1, "b": 2}', object_pairs_hook=OrderedDict)
OrderedDict([('a', 1), ('b', 2)])
>>> json.loads('{"b": 2, "a": 1}', object_pairs_hook=OrderedDict)
OrderedDict([('b', 2), ('a', 1)])

다른 사람들이 언급했듯이 기본 딕트는 순서가 뒤바뀌었다.그러나 파이썬에는 Ordered Dict 객체가 있습니다.(이 객체는 최근 비단뱀에 내장되어 있습니다.또는 http://code.activestate.com/recipes/576693/ 를 사용할 수 있습니다.

새로운 phython json 구현은 Ordered Dicts를 올바르게 처리할 수 있다고 생각합니다만, 확실히는 모르겠습니다(또한 테스트도 쉽지 않습니다).

오래된 phythons simplejson 구현에서는 OrderDict 객체를 적절하게 처리하지 못하고 출력하기 전에 일반 딕트로 변환합니다.다만, 다음의 조작에 의해서, 이 문제를 해결할 수 있습니다.

class OrderedJsonEncoder( simplejson.JSONEncoder ):
   def encode(self,o):
      if isinstance(o,OrderedDict.OrderedDict):
         return "{" + ",".join( [ self.encode(k)+":"+self.encode(v) for (k,v) in o.iteritems() ] ) + "}"
      else:
         return simplejson.JSONEncoder.encode(self, o)

이것으로 얻을 수 있는 것은 다음과 같습니다.

>>> import OrderedDict
>>> unordered={"id":123,"name":"a_name","timezone":"tz"}
>>> ordered = OrderedDict.OrderedDict( [("id",123), ("name","a_name"), ("timezone","tz")] )
>>> e = OrderedJsonEncoder()
>>> print e.encode( unordered )
{"timezone": "tz", "id": 123, "name": "a_name"}
>>> print e.encode( ordered )
{"id":123,"name":"a_name","timezone":"tz"}

원하는 대로 되는 거죠

또 다른 대안은 행 클래스를 직접 사용하도록 인코더를 특화하면 중간 dict 또는 Unordered Dict가 필요하지 않습니다.

이 답변이 늦었다는 것은 알지만 다음과 같이 sort_keys를 추가하고 false를 할당합니다.

json.dumps({'****': ***},sort_keys=False)

이것은 나에게 효과가 있었다.

사전의 순서는 사전이 정의된 순서와 관계가 없습니다.이는 JSON으로 변환된 사전뿐만 아니라 모든 사전에도 해당됩니다.

>>> {"b": 1, "a": 2}
{'a': 2, 'b': 1}

사실, 사전은 도달하기도 전에 "위아래로" 뒤집혔다.json.dumps:

>>> {"id":1,"name":"David","timezone":3}
{'timezone': 3, 'id': 1, 'name': 'David'}

json.http()는 사전의 오더를 유지합니다.텍스트 편집기에서 파일을 열면 볼 수 있습니다.Ordered Dict 발송 여부에 관계없이 주문이 유지됩니다.

단, object_pairs_hook 파라미터를 J.F로 하여 OrderedDict()에 로드하도록 지시하지 않는 한 json.load()는 저장된 객체의 순서를 잃게 됩니다.세바스찬은 위에서 가르쳤다.

그렇지 않으면 저장된 사전 개체를 일반 dict에 로드하고 일반 dict는 주어진 항목의 oder를 보존하지 않기 때문에 순서를 잃게 됩니다.

Michael Anderson의 답변에 기반하지만 어레이에 합격했을 때도 기능합니다.

class OrderedJsonEncoder(simplejson.JSONEncoder):
    def encode(self, o, first=True):
        if type(o) == list and first:
            return '[' + ",".join([self.encode(val, first=False) for val in o]) + ']'
        if type(o) == OrderedDict:
            return "{" + ",".join(
                [self.encode(k, first=False) + ":" + self.encode(v) for (k, v) in o.iteritems()]
            ) + "}"
        else:
            return simplejson.JSONEncoder.encode(self, o)

Python 3.7+ 를 사용하고 있는 경우는, 순서가 유지됩니다.

Python 3.7 이전에 dict는 순서가 보장되지 않았기 때문에 컬렉션이 아닌 한 일반적으로 입력과 출력이 스크램블되었습니다.Ordered Dict가 특별히 요구되었습니다.Python 3.7부터는 일반 dict가 순서 보존이 되었기 때문에 컬렉션을 지정할 필요가 없습니다.JSON 생성 및 해석용 OrderedDict.

https://docs.python.org/3/library/json.html#json.dump

Python 3.6.1:

Python 3.6.1 (default, Oct 10 2020, 20:16:48)
[GCC 7.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import json
>>> json.dumps({'b': 1, 'a': 2})
'{"b": 1, "a": 2}'

Python 2.7.5:

Python 2.7.5 (default, Nov 20 2015, 02:00:19) 
    [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.

>>> import json
>>> json.dumps({'b': 1, 'a': 2})
'{"a": 2, "b": 1}'

언급URL : https://stackoverflow.com/questions/10844064/items-in-json-object-are-out-of-order-using-json-dumps

반응형