C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: We can use regular Python objects like lists and dictionaries when creating JSON strings. Dumps returns a string containing JSON.
ListPython program that uses json module, dumps method
import 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(result)
print("Length:", len(result))
Output
["cat", "frog", "fish", [10, 20, 30]]
Length: 37
Python program that uses json.loads
import json
# 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(result)
print("List length:", len(result))
# Get the sub list from the parsed JSON.
sublist = result[3]
print(sublist)
print("Sublist length:", len(sublist))
Output
['bird', 'frog', 'fish', [10, 9, 8]]
List length: 4
[10, 9, 8]
Sublist length: 3
Here: We open the file important.data. We then pass the file object to json.load, which returns the Python list.
Python program that reads JSON from file on disk
import json
# 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)
Contents: important.data
["important", "data", "file", [10, 20, 0]]
Output
['important', 'data', 'file', [10, 20, 0]]
Result: The Python json module correctly throws an error. This is the JSONDecodeError.
Python program that causes json.decoder error
import json
# An error occurs when the JSON is invalid.
result = json.loads('["invalid JSON data sorry')
Output
Traceback (most recent call last):
...
json.decoder.JSONDecodeError:
Unterminated string starting at: line 1 column 2 (char 1)