python json dump,如何让指定键先行?

时间:2015-05-04 09:04:49

标签: python json

我想将这个json转储到一个文件中:

json.dumps(data) 

这是数据:

 {
       "list":[
        "one": { "id": "12","desc":"its 12","name":"pop"},
        "two": {"id": "13","desc":"its 13","name":"kindle"}
        ]
    }

我希望id成为我将其转储到文件后的第一个属性,但事实并非如此。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

My guess is that it's because you're using a dictionary (hash-map). It's unsortable. What you could do is:

from collections import OrderedDict
data = OrderedDict()
data['list'] = OrderedDict()
data['list']['one'] = OrderedDict()
data['list']['one']['id'] = '12'
data['list']['one']['idesc'] = ...
data['list']['two'] = ...

This makes it sorted by order of input. It's "impossible" to know the output of a dict/hashmap because the nature (and speed) of a traditional dictionary makes the sort/access order vary depending on usage, items in the dictionary and a lot of other factors. So you need to either pass your dictionary to a sort() function prior to sending it to json or use a slower version of the dictionary called OrderedDict (see above).

Many thanks goes out to @MarcoNawijn for checking the source of JSON that does not honor the sort structure of the dictionary, which means you'll have to build the JSON string yourself.

If the parser on the other end of your JSON string honors the order (which i doubt), you could pass this to a function that builds a regular text-string representation of your OrderedDict and formatting the string as per JSON standards. This will however take up more time than I have at this moment since i'm not 100% certain of the RFC for JSON strings.

答案 1 :(得分:0)

您不必担心json的保存顺序。转储时订单将被更改。更好地看看这些。 JSON order mixed upIs the order of elements in a JSON list maintained?