English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
JSON (Java Script Object Notation) est un format de données d'échange léger et reconnu. En utilisant la technologie de format JSON dans Python, nous pouvons convertir une chaîne de caractères JSON en objet Python, ou convertir un objet Python en chaîne de caractères JSON.
Pour utiliser ces fonctionnalités, nous devons utiliser le module json de Python. Le module json est fourni avec la bibliothèque standard de Python. Par conséquent, nous devons d'abord l'importer.
import json
Dans le module json, il y a quelques méthodes, telles que dump() et dumps(), qui peuvent convertir des objets Python en chaînes de caractères JSON. La méthode dump() prend deux paramètres, le premier étant l'objet, le second étant l'objet fichier. Cette méthode convertit l'objet en format JSONFluxSérialiser en objet fichier. De même, la méthode dumps() ne prend qu'un seul paramètre. Ce paramètre est l'objet. Il convertit l'objet en JSONChaîne.
import json from io import StringIO str_io_obj = StringIO() #Use JSON Dump to make StringIO json.dump(["India", "Australia", "Brazil"], str_io_obj) print('StringIO Object value: ') + str(str_io_obj.getvalue()) my_json = { "name" : "Kalyan", "age" : 25, "city" : "Delhi" } print(json.dumps(my_json, indent=4))
Résultat de la sortie
StringIO Object value: ["India", "Australia", "Brazil"] { "name": "Kalyan", "age": 25, "city": "Delhi" }
Dans ce cas, nous allons désérialiser une chaîne de caractères JSON. Il y a deux méthodes différentes. Ce sont load() et load(). Ces deux méthodes prennent en paramètre un fichier JSON. load() convertit les données d'un objet fichier en objet Python, tandis que load() convertit les données de type chaîne de caractères.
import json from io import StringIO str_io_obj = StringIO('["xyz", "abc", "xyz", "pqr"]') #charger à partir de StringIO print('Charger: ' + str(json.load(str_io_obj))) print('Chaine de caractères en Json: ' + str(json.loads('{"xyz" : 1, "abc" : 2, "xyz" : 3, "pqr" : 4}')))
Résultat de la sortie
Charger: ['xyz', 'abc', 'xyz', 'pqr'] Chaine de caractères en Json: {'xyz': 3, 'abc': 2, 'pqr': 4}
La classe JSONEncoder est utilisée pour convertir des objets Python en format JSON. Dans cet exemple, nous verrons comment utiliser JSONEncoder pour convertir des objets complexes en objets de type JSON.
import json class Comp_Encoder(json.JSONEncoder): def default(self, comp_obj): if isinstance(comp_obj, complex): return [comp_obj.real, comp_obj.imag] return json.JSONEncoder.default(self, comp_obj) print(json.dumps(5+8j, cls=Comp_Encoder))
Résultat de la sortie
[5.0, 8.0]
La classe JSONDecoder exécute l'opération inverse.
import json my_str = '{"Asim" : 25, "Priyesh" : 23, "Asim" : "28"' #Décodez JSON en utilisant le JSONDecoder print(json.JSONDecoder().decode(my_str)) print(json.JSONDecoder().raw_decode(my_str))
Résultat de la sortie
{'Asim': '28', 'Priyesh': 23} ({'Asim': '28', 'Priyesh': 23}, 44)