Note that I have more opportunities to use it recently, such as encoding an associative array into JSON and sending it via TCP or UDP, or reading a configuration file written in JSON.
If the data of the associative array is frequently rewritten and you want to send the contents of each array by communication, JSON is convenient.
For example, suppose you want to get some 3D coordinates and store them in an associative array.
>>> import json
>>> list = {'x': 100, 'y': 200, 'z': 300}
>>> json.dumps(list)
'{"x": 100, "y": 200, "z": 300}'
Since this example is simple data, there is no need to bother to make it an associative array, but it is very easy to retrieve data with a key when there are various types of data or when you do not remember the order one by one.
Even when sending JSON-encoded data somewhere via some kind of communication, if you tell the key, the recipient can easily retrieve the data. So, JSON decoding.
Encode the list you used earlier, assign it to a variable, and try decoding it.
>>> import json
>>> list = {'x': 100, 'y': 200, 'z': 300}
>>> enc = json.dumps(list)
>>> print enc
'{"x": 100, "y": 200, "z": 300}'
>>> dec = json.loads(enc)
>>> print dec
{u'y': 200, u'x': 100, u'z': 300}
>>> print dec['x']
100
Like this. After decoding, the order of the elements inside is out of order. Anyway, when referring to it, it is called by the key, so the order does not matter.
Recommended Posts