Home
Python
json: Import JSON, load and dumps
This page was last reviewed on Jul 28, 2023.
Dot Net Perls
Json. With JSON we can store data in an easy-to-parse format. We can encode JSON with Python, and then decode it in JavaScript with a single function call.
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.
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))
["cat", "frog", "fish", [10, 20, 30]] Length: 37
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.
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))
['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.
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)
["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.
import json # An error occurs when the JSON is invalid. result = json.loads('["invalid JSON data sorry')
Traceback (most recent call last): ... json.decoder.JSONDecodeError: 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.