Python JSON
- Previous Page Python Date
- Next Page Python RegEx
JSON is a syntax used for storing and exchanging data.
JSON is a text written in JavaScript Object Notation (JavaScript object notation).
JSON in Python
Python has a module named json
the built-in package, which can be used to process JSON data.
Example
Import json
Module:
import json
Parse JSON - Convert JSON to Python
If there is a JSON string, it can be used json.loads()
method to parse it.
The result will be a Python dictionary.
Example
Convert JSON to Python:
import json # Some JSON: x = '{ "name":"Bill", "age":63, "city":"Seatle"}' # Parse x: y = json.loads(x) # The result is a Python dictionary: print(y["age"])
Convert Python to JSON
If there is a Python object, you can use json.dumps()
method to convert it to a JSON string.
Example
Convert Python to JSON:
import json # Python object (dictionary): x = { "name": "Bill", "age": 63, "city": "Seatle" } # Convert to JSON: y = json.dumps(x) # The result is a JSON string: print(y)
You can convert the following types of Python objects to JSON strings:
- dict
- list
- tuple
- string
- int
- float
- True
- False
- None
Example
Convert Python objects to JSON strings and print the values:
import json print(json.dumps({"name": "Bill", "age": 63})) print(json.dumps(["apple", "bananas"])) print(json.dumps(("apple", "bananas"))) print(json.dumps("hello")) print(json.dumps(42)) print(json.dumps(31.76)) print(json.dumps(True)) print(json.dumps(False)) print(json.dumps(None))
When Python is converted to JSON, Python objects are converted to JSON (JavaScript) equivalents:
Python | JSON |
dict | Object |
list | Array |
tuple | Array |
str | String |
int | Number |
float | Number |
True | true |
False | false |
None | null |
Example
Convert Python objects containing all valid data types:
import json x = { "name": "Bill", "age": 63, "married": True, "divorced": False, "children": ("Jennifer","Rory","Phoebe"), "pets": None, "cars": [ {"model": "Porsche", "mpg": 38.2}, {"model": "BMW M5", "mpg": 26.9} } } print(json.dumps(x))
Format the results
The above example prints a JSON string, but it is not easy to read without indentation and line breaks.
json.dumps()
The method provides parameters to make the results more readable:
Example
Use indent
Parameter defines the indentation number:
json.dumps(x, indent=4)
You can also define separators, the default value is (", ", ": "), which means each object is separated by a comma and space, and keys and values are separated by a colon and space:
Example
Use separators
Parameter to change the default separators:
json.dumps(x, indent=4, separators=(". ", " = "))
Sort the results
json.dumps()
The method provides a parameter to sort the keys in the results:
Example
Use sort_keys
Parameter to specify whether the results should be sorted:
json.dumps(x, indent=4, sort_keys=True)
- Previous Page Python Date
- Next Page Python RegEx