» Quick Introduction to Python » 4. Common Modules » 4.3 json

json

JSON (JavaScript Object Notation), specified by RFC 7159 and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax.

Dictionary to JSON String

import json

d = {"c": 1, "b": 2, "a": 0}
print(json.dumps(d)) # {"c": 1, "b": 2, "a": 0}
print(json.dumps(d, sort_keys=True)) # {"a": 0, "b": 2, "c": 1}

List to JSON String

import json

l = ['foo', {'bar': ('baz', None, 1.0, 2)}]
print(json.dumps(l)) # ["foo", {"bar": ["baz", null, 1.0, 2]}]

Decode JSON String to Dictionary and List

import json

l = json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
print(l) # ['foo', {'bar': ['baz', None, 1.0, 2]}]
print(l[1]) # {'bar': ['baz', None, 1.0, 2]}
print(l[0]) # foo

d = json.loads('{"a": 0, "b": 2, "c": 1}')
print(d) # {'a': 0, 'b': 2, 'c': 1}
print(d["a"]) # 0

Specializing JSON decoding with object_hook

import json

def as_complex(dct):
    if '__complex__' in dct:
        return complex(dct['real'], dct['imag'])
    return dct
result = json.loads('{"__complex__": true, "real": 1, "imag": 2}', object_hook=as_complex)
print(result) # (1+2j)

Code Challenge

Try to modify the code in the editor to make it output the answer.

Loading...
> code result goes here
Prev
Next