KKAIROS
Practical guideIllustrative3 min read

Python json: read JSON text into Python values

The json module converts between JSON text and Python values: object/dict, array/list, string/str, number/int or float, true/false/bool, null/None.

Published:

Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.

TE-41-A: json maps JSON values to Python types, not only objects and arrays

No setup needed: the command below creates what it uses in the throwaway folder.

Command:

python3 -c "import json; v=json.loads('{\"s\":\"x\",\"n\":1,\"f\":1.5,\"b\":true,\"z\":null,\"a\":[1],\"o\":{}}'); print(type(v).__name__, type(v['s']).__name__, type(v['n']).__name__, type(v['f']).__name__, type(v['b']).__name__, v['z'], type(v['a']).__name__, type(v['o']).__name__)"

Recorded output:

dict str int float bool None list dict

TE-41-B: dumps writes null and true in lower case and escapes non-ASCII text unless ensure_ascii is False

Setup for this run, inside a throwaway directory (mktemp -d):

cat > s.py <<'EOS'
import json
print(json.dumps({'a': [1, None, True]}))
print(json.dumps('\u00e9'))
print(json.dumps('\u00e9', ensure_ascii=False))
EOS

Command:

python3 s.py

Recorded output:

{"a": [1, null, true]}
"\u00e9"
"é"

Exit status: 0. The output matches the expected text written before the run.

TE-41-C: expected non-zero exit: loads on invalid JSON raises JSONDecodeError with the position

Setup for this run, inside a throwaway directory (mktemp -d):

cat > s.py <<'EOS'
import json
json.loads('{bad')
EOS

The file ../err.txt sits one level above the working folder, inside the same throwaway tree. The output block below shows only the last line of the error; the full traceback went to ../err.txt.

Command:

python3 s.py 2>../err.txt; rc=$?; tail -n 1 ../err.txt; exit $rc

Recorded output:

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Exit status: 1. This status and the output match what was written before the run.

Reading the recorded output

The input is a JSON object with seven keys. The printed line has eight values, separated by spaces. The first is dict, the type of the whole result. Then the types of the values for the keys s, n, f and b: str, int, float and bool. The sixth value is None, the Python value for the JSON null under the key z, printed as the value itself and not as a type name. The last two are list, for the array, and dict, for the empty object.

TE-41-B: dumps wrote None as null and True as true. The text with the character e acute printed as "\u00e9" by default and as "é" with ensure_ascii=False. TE-41-C: loads on {bad stopped with JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1), and exit status 1.

Ad

Limits

load/loads read, dump/dumps write.

Source

Evidence

Evidence table

| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-41-A | json maps JSON values to Python types, not only objects and arrays | 0 | PASS | f664a34c3f50 | | TE-41-B | dumps writes null and true in lower case and escapes non-ASCII text unless ensure_ascii is False | 0 | PASS | 8b769ece210e | | TE-41-C | expected non-zero exit: loads on invalid JSON raises JSONDecodeError with the position | 1 | PASS | 6dbbf889a1eb |

Every row has a recorded log holding the setup commands, the command, stdout, stderr, exit status and the final directory state. The first 12 characters of the log's sha256 are in the table.

All full guides: All guides