JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write. It is also easy for machines to parse and generate. In Python, you can work with JSON data using the built-in `json` module.
JSON Syntax
JSON data is represented as key-value pairs, similar to Python dictionaries. JSON keys are always strings, and values can be strings, numbers, objects, arrays, `true`, `false`, or `null`. Here's a basic example of JSON data:
{
"name": "John",
"age": 30,
"city": "New York"
}
JSON in Python
To work with JSON in Python, you need to import the `json` module. Here's how you can encode Python data into JSON:
Decoding JSON You can also decode JSON data in Python using the json.loads()
function. Here's an example:
The json.loads()
function takes a JSON string and converts it into a Python object.
Working with JSON Files
JSON is commonly used for data storage and exchange. You can read and write JSON data from/to files in Python. Here's an example of reading JSON data from a file
And here's an example of writing JSON data to a file:
Handling JSON Errors
Handling JSON Errors When working with JSON data, it's important to handle errors gracefully. JSON decoding can raise json.JSONDecodeError
if the input is not valid JSON. Here's how to handle it:
Last updated