Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

json

I have problem when I want to convert json string to Python dictionary. I have string like

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

when I write something like

tags=json.loads(s)

I gtet dictionary but order of keys is not the same like in string ( it is not name, price ...). How to convert json string to dictionary and save order in keys ?

like image 254
Damir Avatar asked Apr 18 '12 09:04

Damir


1 Answers

Since Python 2.7 you have OrderedDict module from collections

This kind of dictionary preserves the insertion order of elements.

From Python docs:

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.

I think you could use object_pairs_hook parameter with collections.OrderedDict()

tags=json.loads(s, object_pairs_hook=collections.OrderedDict)
like image 86
Diego Navarro Avatar answered Oct 10 '22 23:10

Diego Navarro