The json module in Python provides methods for encoding and decoding JSON data. Here's an example of how you can use the json module to read the "items.json" file and parse its contents into a Python data structure:
import jsonwith open('items.json', 'r') as f: items = json.load(f)print(items) |
In this example, the json.load() method is used to parse the contents of the "items.json" file into a Python data structure. The resulting items variable is a list of dictionaries, where each dictionary corresponds to one of the objects in the original JSON file.
You can then manipulate this data structure in your Python program, for example by iterating over the items in the list and printing out their names:
for item in items: print(item['name']) |
This would output:
AppleBananaOrange |
Similarly, you can use the json.dump() method to write a Python data structure to a JSON file:
items = [ {'id': 4, 'name': 'Pear', 'price': 0.60, 'description': 'Juicy and sweet pears from the local farm.'}, {'id': 5, 'name': 'Grapefruit', 'price': 0.80, 'description': 'Tangy grapefruit from the grove down the road.'}]with open('new_items.json', 'w') as f: json.dump(items, f) |
This code would create a new JSON file called "new_items.json" and write the contents of the items variable to it in JSON format.