###### tags: `Classical Computing`
# Storing parameters to JSON by python
## About JSON
JSON (JavaScript Object Notation) is a format file to store data (as list or dict, etc).
## How to output
We can store parameters to JSON files which will be made in the same directory of the python files.
### Output dicts
```python=
import json
l = {3:4,6:7}
with open('1_test.json', 'w') as f:
json.dump(l, f, ensure_ascii=False)
```
Result
```
# 1_test.json
{3:4, 6:7}
```
Attention:
When defining as follwing, EOF errors occur.
```python=
l = {3,7}
```
### Output lists
```python=
import json
l = [[1,2],3]
with open('2_test.json', 'w') as f:
json.dump(l, f, ensure_ascii=False)
```
Result
```
# 1_test.json
{0:{0:1,0:2}, 1:3}
```
### Output inputs and returns of functions
We can also get inputs and returns of functions and store them to JSON files.
```python=
def Sum(a,b):
return a+b
for a in (0,1,2):
for b in (3,4):
json_file = '3_test_{}{}.json'.format(a,b)
ans = Sum(a,b)
mem = {"params":{1:a,2:b},"ans":ans}
with open(json_file, 'w') as f:
json.dump(mem, f, ensure_ascii=False, indent=4)
```
## How to output using pickle
The following is not nessesarry for reading about JSON outputs. It's just a memorandom for pickle.
Pickle is a binary file for storing lists and sets but is not readable. To read pickle files, we make JSON files which corresponds to it.
### Output lists and sets
```python=
import pickle
import json
l = [[1,2],3]
with open('4_pic.bin', 'wb') as p:
pickle.dump(l, p)
with open('4_pic.bin', 'rb') as p:
l = pickle.load(p)
with open('4_test_auto.json', 'w') as f:
json.dump(l, f, ensure_ascii=False, indent=4)
```
The above is for outputing lists but we can do it as the same for sets.
### Output parameters and returns of functions
```python=
import pickle
import json
def Sum(a,b):
return a+b
for a in (0,1,2):
for b in (3,4):
pickle_file = "func_pic_{}{}.bin".format(a,b)
json_file = 'test_{}{}.json'.format(a,b)
ans = Sum(a,b)
mem = {"params":{1:a,2:b},"ans":ans}
with open(pickle_file, 'wb') as p:
pickle.dump(mem, p)
with open(pickle_file, 'rb') as p:
t = pickle.load(p)
print(t)
with open(json_file, 'w') as f:
json.dump(t, f, ensure_ascii=False, indent=4)
```