JSON¶
Python has a built-in package called json, which can be used to work with JSON data.
Convert from JSON to Python
If you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python object
.
dumps and loads¶
>>> import json
>>> x = '{ "name":"John", "age":30, "city":"New York"}'
>>> y = json.loads(x)
>>> print(y)
{u'city': u'New York', u'age': 30, u'name': u'John'}
If you have a Python object, you can convert it into a JSON string
by using the json.dumps()
method.
>>> x = {'city': 'New York', 'age': 30, 'name': 'John'}
>>> json.dumps(x)
'{"city": "New York", "age": 30, "name": "John"}'
dump and load¶
To create a JSON object from a file
>>> with open('data.txt', 'w') as outfile:
... json.dump(data, outfile)
To createt a JSON file from a python object
>>>with open('data.txt', 'w') as outfile:
... json.dump(data, outfile)
Pretty printing¶
>>> import json
>>> data = {'people':[{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}]}
>>> json.dumps(data, indent=4)
{
"people": [
{
"website": "stackabuse.com",
"from": "Nebraska",
"name": "Scott"
}
]
}
Sorting¶
In JSON, an object is defined as: an unordered set of name/value pairs
So the standard is saying that key order isn't guaranteed, but it's possible that you may need it for your own purposes internally. To achieve ordering, you can pass True to the sort_keys option when using json.dump or json.dumps.
>>> import json
>>> data = {'people':[{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}]}
>>> json.dumps(data, sort_keys=True, indent=4)
{
"people": [
{
"from": "Nebraska",
"name": "Scott",
"website": "stackabuse.com"
}
]
}
>>> json.dumps(data, sort_keys=True,indent=2,separators=(',',':'))
{
"people":[
{
"from":"Nebraska",
"name":"Scott",
"website":"stackabuse.com"
}
]
}