JSON (JavaScript Object Notation) is a popular data format used for representing structured data. It’s commonly used for transmitting data in web applications (e.g., sending data from the server to the client) and for configuration files. JSON is a text-only format and can be easily used in any programming language including Python.
Here is a simple guide on how to use JSON files in Python:
1. Importing JSON Module:
First, we need to import Python’s built-in `json` module.
```
import json
```
1. Reading JSON Data:
To decode or “parse” JSON data, we can use the `json.load()` method (if it’s a file) or the `json.loads()` method (if it’s a string).
```
with open(‘file.json’) as f:
data = json.load(f)
data = json.loads(json_string)
```
1. Writing JSON Data:
You can convert Python objects of the following types, into JSON strings by using the `json.dump` method for files and `json.dumps` method for strings:
- dict
- list
- tuple
- string
- int
- float
- True
- False
- None
```
data = {
“name”: “John”,
“age”: 30,
“city”: “New York“
}
with open(‘file.json’, ‘w’) as f: json.dump(data, f)
json_string = json.dumps(data)
```
The `json.dump()` and `json.dumps()` methods have parameters to customize the output. The parameters `indent`, `separators` and `sort_keys` must be named.
1. Python supports a Python proprietary data serialization method called pickle (and a faster alternative called cPickle).
You can use it exactly the same way.
```
import pickle
#load from file
obj = pickle.load(file)
```
Notice that it does not save to JSON. It saves to pickle format. But you still can change to JSON:
```
import json
import pickle
#convert obj to JSON formatted string
json_str = json.dumps(obj)
#load JSON
obj = json.loads(json_str)
```