21 novembre 2017 / Viewed: 19076 / Comments: 0 / Edit
Considérons un fichier JSON (JavaScript Object Notation) intitulé data.json avec les données suivantes:
{
"abstract": "Hello how are you today ?",
"link_01": {
"name": "Welcome page",
"priority": "1"
},
"link_02": {
"name": "Home page",
"priority": "2"
}
}
Pour lire le fichier avec python on peut alors procéder comme suit:
with open('data.json') as json_data:
print(type(json_data))
donne ici
<class '_io.TextIOWrapper'>
Pour stocker les données du fichier JSON dans un dictionnaire python il existe la fonction load() du module python json, illustration:
import json
with open('data.json') as json_data:
data_dict = json.load(json_data)
print(data_dict)
donne ici comme résultat:
{'abstract': 'Hello how are you today ?', 'link_02': {'priority': '2', 'name': 'Home page'}, 'link_01': {'priority': '1', 'name': 'Welcome page'}}
Une fois les données dans le dictionnaire que nous avons intitulé data_dict il est alors possible de stocker les données dans une chaine de caractères data_str en passant par la fonction dumps:
import json
with open('data.json') as json_data:
data_dict = json.load(json_data)
data_str = json.dumps(data_dict)
print(data_str)
donne
{"abstract": "Hello how are you today ?", "link_02": {"name": "Home page", "priority": "2"}, "link_01": {"name": "Welcome page", "priority": "1"}}
Attention si on veut remettre les données dans un dictionnaire a partir d'une chaine de caractères il faut utiliser la fonction fonction loads() et pas load() comme précédemment, exemple:
import json
with open('data.json') as json_data:
data_dict = json.load(json_data)
data_str = json.dumps(data_dict)
data_dict_02 = json.loads(data_str)
print(data_dict_02)
Liens | Site |
---|---|
Importing JSON file with python | stackoverflow |
Reading and Writing JSON to a File in Python | stackabuse.com |
JSON - Introduction | w3schools |
Parsing JSON | docs.python-guide.org |
Parsing values from a JSON file? | stackoverflow |
Reading JSON from a file? | stackoverflow |
JSON encoding and decoding with Python | pythonspot |
parse JSON values by multilevel keys | stackoverflow |
Working with JSON and Django | godjango |
How can I edit/rename keys during json.load in python? | stackoverflow |
Items in JSON object are out of order using “json.dumps”? | stackoverflow |
json.dumps messes up order | stackoverflow |
JSON Example | json.org |
circlecell/jsonlint.com | jsonlint.com |
jsonlint | jsonlint |
zaach/jsonlint | jsonlint github |
Je développe le présent site avec le framework python Django. Je m'intéresse aussi actuellement dans le cadre de mon travail au machine learning pour plusieurs projets (voir par exemple) et toutes suggestions ou commentaires sont les bienvenus !