Archivos .json#
Ultima modificación: Mayo 14, 2022
Parámetros#
[1]:
#
# Se almacenan como diccionarios
#
params = {
"as_dict": {
"host": "localhost",
"port": 8082,
},
"as_list": [
"value 0",
"value 1",
"value 2",
],
"as_integer": 100,
"as_float": 1.0,
}
params
[1]:
{'as_dict': {'host': 'localhost', 'port': 8082},
'as_list': ['value 0', 'value 1', 'value 2'],
'as_integer': 100,
'as_float': 1.0}
Escritura del archivo de configuración#
[2]:
import json
with open("config.json", "w") as out_file:
json.dump(params, out_file)
[3]:
!cat config.json
{"as_dict": {"host": "localhost", "port": 8082}, "as_list": ["value 0", "value 1", "value 2"], "as_integer": 100, "as_float": 1.0}
[4]:
with open("config.json", "w") as out_file:
json.dump(
params,
fp=out_file,
indent=4,
sort_keys=True,
)
[5]:
!cat config.json
{
"as_dict": {
"host": "localhost",
"port": 8082
},
"as_float": 1.0,
"as_integer": 100,
"as_list": [
"value 0",
"value 1",
"value 2"
]
}
Lectura desde un archivo#
[6]:
with open('config.json', 'r') as in_file:
params = json.load(in_file)
params
[6]:
{'as_dict': {'host': 'localhost', 'port': 8082},
'as_float': 1.0,
'as_integer': 100,
'as_list': ['value 0', 'value 1', 'value 2']}
Lectura en la linea de comandos#
[7]:
!python3 -m json.tool config.json
{
"as_dict": {
"host": "localhost",
"port": 8082
},
"as_float": 1.0,
"as_integer": 100,
"as_list": [
"value 0",
"value 1",
"value 2"
]
}
[8]:
!rm config.json