Python - Json

1 - From Json to Python

1.1 - Load (Load an object)

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

For json.load, you should pass a file like object with a read function defined.


1.2 - Loads (Load a String)

thejson_string = '["foo", {"bar":["baz", null, 1.0, 2]}]'
dictio = json.loads(thejson_string) 
for key in dictio:
    print "Type:", type(key)
    print "Key:", key
Type: <type 'unicode'>
Key: foo
Type: <type 'dict'>
Key: {u'bar': [u'baz', None, 1.0, 2]}

2 - From obj to JSon

2.1 - Dumps (Dump a string)

Serialize (transform) obj to a JSON formatted str

2.1.1 - Beautify Pretty printing

From a dictionary to a json string:

import json
the_dic = {'Name':'Gerard','Nickname':'Nico'}
print type(the_dic)
pretty_json = json.dumps(the_dic, sort_keys=True,indent=4, separators=(',', ': '))
print pretty_json
print type(pretty_json)
<type 'dict'>
    "Name": "Gerard",
    "Nickname": "Nico"
<type 'str'>

3 - Documentation / Reference

lang/python/json.txt ยท Last modified: 2017/02/17 19:26 by gerardnico