Welcome to the JSON Module lesson! In this tutorial, we'll dive into the world of working with JSON data in Python. This lesson is perfect for both beginners and intermediates. Let's get started!
JSON (JavaScript Object Notation) is a lightweight data interchange format that's easy for humans to read and write and easy for machines to parse and generate. It's commonly used for asynchronous browser/server communication, and is supported by almost all programming languages.
Python's built-in json module allows you to work with JSON data easily. Let's explore how to use this module to load, parse, and manipulate JSON data.
To load JSON data in Python, you can use the json.load() function. This function reads a JSON file and returns a Python dictionary.
Here's an example:
import json
data = json.load(open('data.json'))
print(data)Replace 'data.json' with the path to your JSON file. The code above reads the JSON file and prints the data as a Python dictionary.
What does `json.load()` do in Python?
If you have a JSON string, you can parse it into a Python object using the json.loads() function.
Here's an example:
import json
json_data = '{"name": "John", "age": 30}'
data = json.loads(json_data)
print(data)The code above parses the JSON string and prints the data as a Python dictionary.
Once you have JSON data as a Python object, you can manipulate it just like any other Python object. Let's modify the example from the previous section:
import json
json_data = '{"name": "John", "age": 30}'
data = json.loads(json_data)
data['age'] = 31
json_data_updated = json.dumps(data)
print(json_data_updated)The code above modifies the 'age' key in the JSON data and converts the updated Python object back to a JSON string.
How can you modify a JSON object in Python?
To write JSON data to a file, you can use the json.dump() function. This function takes a Python object and writes it to a JSON file.
Here's an example:
import json
data = {'name': 'Jane', 'age': 25}
with open('output.json', 'w') as f:
json.dump(data, f)The code above writes the Python object to a JSON file named output.json.
And that's it! You now have a good understanding of how to work with JSON data in Python. Happy coding! 🎉