Python for AI: A Crash Course

Nov 16 2024 · Python 3.12, JupyterLab 4.2.4

Lesson 04: Working with Local Data (File Operations & Data Handling)

JSON Files Demo

Episode complete

Play next episode

Next
Transcript

Demo

In this demo, you’ll write code to write and read JSON files, just as you did for text and CSV files.

Writing To a JSON File

Start by writing a JSON file to your computer’s filesystem so you’ll have one to read later.

Open the working-with-files-starter.ipynb notebook. Once again, you’ll write the data in the programming_languages list to a file, but this time, it’ll be a JSON file.

Scroll to the Working with JSON Files section of the notebook. Enter the following into a new code cell and run it:

import json

with open("programming-languages.json", "w") as file:
  json.dump(programming_languages, file, indent=4, ensure_ascii=False)

The json.dump() method takes a Python data structure and writes it to a file in JSON form. Here’s a quick description of the arguments passed to it:

  • programming_languages: The first argument to json.dump() is the data structure to be written to the JSON file. This is required.
  • file: The second argument is the file object for the JSON file. This is also required.
  • indent: This is an optional argument, but it’s recommended. It formats the JSON file with indentation so that it’s easier for humans to read. The 4 specifies that each level of indentation uses four spaces, which is the generally accepted form of indentation for Python.
  • ensure_ascii: This is also optional but recommended. Setting this value to False allows the JSON file to use the full Unicode set of characters and not just the ASCII set, which you want if you want your application to support every language and emoji.

Open programming-languages.json with the JupyterLab text editor. You’ll see the data from the programming_languages list of dictionaries in JSON form. Click the triangles to view items deeper in the hierarchy.

Reading From a JSON File

Now, read the JSON file you just created. Run the following in a new code cell:

with open("programming-languages.json", "r") as file:
  data = json.load(file)
  print(data)

The json.load() method takes a file object, reads the JSON file associated with that object, and then decodes the file’s data into a Python data structure.

The output is a ‘data dump’ and not very pretty. Format the output with json.dumps() by running the following code:

with open("programming-languages.json", "r") as file:
  data = json.load(file)
  json_string = json.dumps(data, indent=4)
  print(json_string)

Now, the output is easily readable.

Finally, there’s always a chance that the JSON could be poorly formatted, which would lead to an error in decoding, which raises a json.JSONDecodeError exception. It’s generally a good idea to incorporate exception handling when reading JSON files.

Enter the following into a new code cell:

try:
  with open("programming-languages.json", "r") as file:
    data = json.load(file)
    json_string = json.dumps(data, indent=4)
    print(json_string)
except json.JSONDecodeError as e:
  print(f"JSON decoding error: {e}")
except FileNotFoundError as e:
  print(f"File not found! Details:\n{e}")
except OSError as e:
  print(f"I/O error (probably)! Details:\n{e}")
except Exception as e:
  print("An unexpected error occurred! Call the developer.")
  print(f"Details:\n{e}")
else:
  print("Congratulations! No errors!")
finally:
  print("All done.")

If you run the cell, it should simply display the data structure representing the JSON data from the file. To see the exception handling in action, open programming-languages.json in a text editor, corrupt it by removing a comma or two, save the change, and rerun the code cell. You should see the text JSON decoding error: followed by more specific information about the exception.

See forum comments
Cinema mode Download course materials from Github
Previous: JSON Files Next: Conclusion