eolas/zk/Working_with_JSON_in_Python.md

32 lines
825 B
Markdown
Raw Permalink Normal View History

2024-06-25 06:45:05 +01:00
---
tags: [python, JSON]
created: Tuesday, June 25, 2024
---
# Working with JSON in Python
## `json.loads()`
Convert a string containing JSON data into the native Python dictionary object.
Equivalent to `JSON.parse()` in JavaScript.
Will error if the input string is not properly formatted JSON. This will be
`json.JSONDecodeError`, a subclass of the `ValueError`
[exception](./Error_handling_in_Python.md)
2024-06-25 07:00:03 +01:00
## `json.dumps()`
2024-06-25 06:45:05 +01:00
Take a JSON-formatted dictionary and convert it into a string. The reverse of
`json.loads()` and equivalent to `JSON.stringify()` in JavaScript.
2025-01-01 15:57:56 +00:00
## `json.dump()`
2024-06-25 06:45:05 +01:00
2025-01-01 15:57:56 +00:00
Not to be confused with the above. Output a Python dictionary as JSON, for
instance to create a `.json` file:
2024-06-25 06:45:05 +01:00
2025-01-01 15:57:56 +00:00
```py
data = { "key": "value"}
with open("some/directory/output.json", "w") as f:
json.dump(data, f, indent=4)
```