18d41550de
Signed-off-by: David Rotermund <54365609+davrot@users.noreply.github.com> |
||
---|---|---|
.. | ||
README.md |
JSON and dict
{:.no_toc}
* TOC {:toc}The goal
A combination of JSON (JavaScript Object Notation) file and dictionaries allows to organize parameters in an external file.
Questions to David Rotermund
json -- JSON encoder and decoder
dump
import json
a = dict(one=1, two=2, three=3)
with open("data_out.json", "w") as file:
json.dump(a, file)
Content of data_out.json:
{"one": 1, "two": 2, "three": 3}
load
import json
with open("data_out.json", "r") as file:
b = json.load(file)
print(b)
Output:
{'one': 1, 'two': 2, 'three': 3}
jsmin and loads
pip install jsmin
Maybe you want to have comments in your config file.
Content of data_in.json:
// This an important comment...
{
"one": 1,
"two": 2,
"three": 3
}
Note for VS Code: You need to change the filetype from JSON to JSON with comments. Lower right corner.
The normal JSON functions fails:
import json
with open("data_in.json", "r") as file:
b = json.load(file)
print(b)
Output:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
With jsmin:
import json
from jsmin import jsmin
with open("data_in.json", "r") as file:
minified = jsmin(file.read())
b = json.loads(minified)
print(b)
Output:
{'one': 1, 'two': 2, 'three': 3}