All questions

How do I read and parse a JSON file safely in Python?

Answer

Open the file with an explicit encoding inside a `with` block and catch the two errors that matter: a missing file and invalid JSON. - `FileNotFoundError` means the path is wrong. - `json.JSONDecodeError` carries the line and column of the problem. - Use `pathlib.Path` to build paths that work on Windows, macOS and Linux.

Python solution

import json
from pathlib import Path

def load_json(path):
    file = Path(path)
    try:
        with file.open(encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        print(f'File not found: {file}')
    except json.JSONDecodeError as err:
        print(f'Invalid JSON at line {err.lineno}, column {err.colno}: {err.msg}')
    return None

data = load_json('config.json')
if data is not None:
    print(data.get('name', 'unnamed'))

Edited by Jack · joysait@rediffmail.com

Add a Q&A

Drop an image here or click to choose. It is saved as images/N.ext.

Live preview

Publish to GitHub

Drafts 0

Drafts live in this browser only. Download or push them to make them public.

    Files to commit

    data/qa.json
    sitemap.xml
    robots.txt

    Push with the GitHub API

    Uses a fine-grained token with Contents: Read and write on your repo. The token stays in this page's memory only: it is never saved or sent anywhere except api.github.com.