关于python:如何将json字符串转换为字典并保存键中的顺序?

How to convert json string to dictionary and save order in keys?

本问题已经有最佳答案,请猛点这里访问。

当我想将JSON字符串转换为python字典时,我遇到了问题。我有线绳

1
 s={"name":{"Saban:Saulic"},"price":{"koncert:1000"} ....}

当我写一些像

1
tags=json.loads(s)

i gtet字典,但键的顺序与字符串中的顺序不同(它不是名称、价格…)。如何将JSON字符串转换为字典并保存键顺序?


从python 2.7开始,您就有了来自collectionsOrderedDict模块。

这种字典保留元素的插入顺序。

从python文档:

json.load(fp[, encoding[, cls[, object_hook[, parse_float[,
parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

Deserialize fp (a .read()-supporting file-like object containing a
JSON document) to a Python object.

If the contents of fp are encoded with an ASCII based encoding other
than UTF-8 (e.g. latin-1), then an appropriate encoding name must be
specified. Encodings that are not ASCII based (such as UCS-2) are not
allowed, and should be wrapped with codecs.getreader(encoding)(fp), or
simply decoded to a unicode object and passed to loads().

object_hook is an optional function that will be called with the
result of any object literal decoded (a dict). The return value of
object_hook will be used instead of the dict. This feature can be used
to implement custom decoders (e.g. JSON-RPC class hinting).

object_pairs_hook is an optional function that will be called with the
result of any object literal decoded with an ordered list of pairs.
The return value of object_pairs_hook will be used instead of the
dict. This feature can be used to implement custom decoders that rely
on the order that the key and value pairs are decoded (for example,
collections.OrderedDict() will remember the order of insertion). If
object_hook is also defined, the object_pairs_hook takes priority.

我想你可以在collections.OrderedDict()中使用object_pairs_hook参数。

1
tags=json.loads(s, object_pairs_hook=collections.OrderedDict)