json.dumps code example

Example 1: print json python

import json

uglyjson = '{"firstnam":"James","surname":"Bond","mobile":["007-700-007","001-007-007-0007"]}'

#json.load method converts JSON string to Python Object
parsed = json.loads(uglyjson)

print(json.dumps(parsed, indent=2, sort_keys=True))

Example 2: python json string to object

import json

x =  '{ "name":"John", "age":30, "city":"New York"}'
y = json.loads(x)

print(y["age"])

Example 3: python json dump format

>>> import json
>>>
>>> your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(parsed, indent=4, sort_keys=True))
[
    "foo", 
    {
        "bar": [
            "baz", 
            null, 
            1.0, 
            2
        ]
    }
]

Example 4: python json.dumps pretty print

json.dumps(x, indent=4)

Example 5: python json dump

import json

with open("data_file.json", "w") as write_file:
    json.dump(data, write_file)

Example 6: json load

import json

with open('path_to_file/person.json') as f:
  data = json.load(f)

Tags: