Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Pretty Print JSON In Python

Use `sort_keys`, `indent`, and `default` to pretty print JSON from Python

Code

import json

json_structure = { 
  "metadata": { "version": "0.1.0" }
}

json_string = json.dumps(
    json_structure, 
    sort_keys=True, 
    indent=2, 
    default=str
)

print(json_string)

Results

{
  "metadata": {
    "version": "0.1.0"
  }
}

The `default=str` argument prefents issues when converting Date objects.