---
# System prepended metadata

title: Json and pickle - Data Persistence

---

# Json and pickle - Data Persistence

## Json
### `import json`
json stores data in string format

json is also how some servers are able to communicate with each other, which is where you will also see instances of json in the [request.md](https://hackmd.io/@eleans412/Bkh0hTFrd )

#### Reading json 
```
with json.open('database.json', 'r'):
```
* The `'with'` looks for what method you are looking to use, in this instance json or pickle
* `'open'` opens up the file that you want to read from
* `'database.json'` is the file that you want to read from (this has to be in your directory for you to read from)
* `'r'` means that you want to read from it

When you read from a json file you are able to loop through and iterate through the contents there - this is what we did when we implemented data persistence

#### Dumping in json
```
with json.open('database.json', 'w'):
    dumps(data)
```
* The `'with'` looks for what method you are looking to use, in this instance json or pickle
* `'open'` opens up the file that you want to read from
* `'database.json'` is the file that you want to write to (this creates the file if it does not already exist in your directory)
* `'w'` means that you want to write to it from it
* `'dumps'` puts all the stuff you want to add to the `.json` file into it


## Pickle
### `import pickle`

Pickle stores data in binary form - this makes the data more compact 

The way we access the data is similar to json, with some adjustments for the binary format of pickle

#### Reading pickle 
```
with pickle.open('database.p', 'rb'):
```
* The `'with'` looks for what method you are looking to use, in this instance json or pickle
* `'open'` opens up the file that you want to read from
* `'database.p'` is the file that you want to read from (this has to be in your directory for you to read from)
* `'rb'` means that you want to read from it
    * there is as you are converting what was binary back to something we can read

When you read from a json file you are able to loop through and iterate through the contents there - this is what we did when we implemented data persistence

#### Writing to pickle
```
with json.open('database.p', 'wb'):
    dumps(data)
```

* The `'with'` looks for what method you are looking to use, in this instance json or pickle
* `'open'` opens up the file that you want to read from
* `'database.p'` is the file that you want to write to (this creates the file if it does not already exist in your directory)
* `'wb'` means that you want to write to it from it
    * this is as you are writing in binary
* `'dumps'` puts all the stuff you want to add to the `.p` file into it