Lire un fichier JSON
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'>
Mettre les données dans un dictionnaire
Pour stocker les données du fichier JSON dans un dictionnaire python il existe la fonction load() du module python json, illustration:
import jsonwith 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'}}
Mettre les données dans une chaine de caractères
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 jsonwith 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"}}
Remettre les données dans un dictionnaire
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 jsonwith 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)
Références
| 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 |
