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

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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.

import json

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

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)
with open("programming-languages.json", "r") as file:
  data = json.load(file)
  json_string = json.dumps(data, indent=4)
  print(json_string)
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.")
See forum comments
Cinema mode Download course materials from Github
Previous: JSON Files Next: Conclusion