JSON files¶
- It is common to store data in a file in a format that is easy to read, both for people and machines.
- One such format is JSON.
- This has many uses, but a common one is to store user variables that control how a code is run, without having to change the code itself, only the input file.
- JSON files make use of key-value pairs, like dictionaries.
- values can be numbers, strings, arrays, true/false, null, or dictionaries (called objects), also null.
- Don't forget to end lines with commas, except for the last element in an object.
- Here's a very short tutorial
Example file¶
In [23]:
%pycat input.json
{
"Ldomain": 0.01,
"Li": 0.01,
"k": 1.0,
"nu": 1.5E-5,
"tRun": 0.1,
"N_eta": 10.76,
"C_lambda": 15,
"dtFactor": 0.5,
"dtWrite": 0.001,
"doRxn": false,
"Tbounds": [300, 2500],
"mech": null,
"thermo": {
"mech": "gri30.yaml",
"P": 101325,
"T0": 300,
"X0": "O2:1, N2:7.52",
"T1": 300,
"X1": "CH4:1"
},
"Vars": {
"scal": {
"D": 2.24E-5,
"BC": {
"loType": "D",
"hiType": "D",
"lo": 0.0,
"hi": 1.0
}
},
"ygas": {
"BC": {
"loType": "D",
"hiType": "D"
}
},
"enth": {
"BC": {
"loType": "D",
"hiType": "D"
}
}
}
}
Read data from a JSON file¶
In [ ]:
import json
with open("input.json", "r") as ifile:
data = json.load(ifile)
data.keys()
# access data in the file using dictionary syntax:
Ldomain = data["Ldomain"]
rxns = data["doRxn"]
scalBClo = data["Vars"]["scal"]["BC"]["lo"]
In [ ]: