pytutorial/python_basics/json
David Rotermund a0935be422
Create README.md
Signed-off-by: David Rotermund <54365609+davrot@users.noreply.github.com>
2023-12-12 23:13:30 +01:00
..
README.md Create README.md 2023-12-12 23:13:30 +01:00

JSON and dict

{:.no_toc}

* TOC {:toc}

The goal

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: 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}