Improve compatibility. By using JSON we have fewer compatibility issues. We do not need to create special file formats (or we can store those formats inside JSON for simplicity).
Json.dumps. Python has built-in support for JSON. Consider this program. We import the json module and call its dumps() method. We have 2 Python lists we pass to dumps().
Tip We can use regular Python objects like lists and dictionaries when creating JSON strings. Dumps returns a string containing JSON.
# A list with a nested list.
sublist = [10, 20, 30]
list = ["cat", "frog", "fish", sublist]
# Call dumps on our list.
result = json.dumps(list)
# Display the JSON data.
print("Length:", len(result))["cat", "frog", "fish", [10, 20, 30]]
Json.loads. With loads we can parse a JSON string and have Python objects like a list in our program. Loads() parses JSON. The JSON must be formatted correctly.
# A JSON string must use double-quotes.# ... We place the JSON data inside single-quotes here.
result = json.loads('["bird", "frog", "fish", [10, 9, 8]]')
# Print the resulting list.
print("List length:", len(result))
# Get the sub list from the parsed JSON.
sublist = result
print("Sublist length:", len(sublist))['bird', 'frog', 'fish', [10, 9, 8]]
List length: 4
[10, 9, 8]
Sublist length: 3
File load. With json.load we can read in JSON data from a file and parse it. Load() is different from the json.loads() method. It requires a file object.
Here We open the file important.data. We then pass the file object to json.load, which returns the Python list.
# Use open to get a file object for a JSON file.
f = open(r"C:\programs\important.data", "r")
# Use json.load to parse the data.
result = json.load(f)
# Print the resulting Python list.
print(result)["important", "data", "file", [10, 20, 0]]['important', 'data', 'file', [10, 20, 0]]
JSONDecodeError. JSON must be valid. It provides no recovery for invalid files. Here we try to decode an invalid JSON file (one with a string that is not terminated).
Result The Python json module correctly throws an error. This is the JSONDecodeError.
# An error occurs when the JSON is invalid.
result = json.loads('["invalid JSON data sorry')Traceback (most recent call last):
Unterminated string starting at: line 1 column 2 (char 1)
A summary. JSON is used for its extreme simplicity. It is compatible with all modern web browsers—no custom code is needed to handle JSON inside Chrome. This is a key advantage.