Dans cet article, nous verrons différentes manières de convertir une chaîne en JSON en Python. Ce processus est appelé sérialisation. Le module JSON fournit des fonctions pour encoder (sérialiser) des objets Python dans JSON chaînes et décodage (désérialisation) des chaînes JSON en Objets Python .
- Encodage (sérialisation) JSON : Si vous avez un objet Python et que vous souhaitez le convertir en chaîne JSON, vous pouvez utiliser le json.dumps() fonction. Il prend l'objet Python en entrée et renvoie une chaîne JSON.
- Décodage (désérialisation) JSON : Si vous disposez d'une chaîne JSON et que vous souhaitez la convertir en objet Python, vous pouvez utiliser le json.loads() fonction. Il prend la chaîne JSON en entrée et renvoie un objet Python.
Convertir une chaîne en objet JSON en Python
Vous trouverez ci-dessous des méthodes pour convertir des chaînes Python en objets JSON :
- En utilisant json.loads() Méthode
- Utilisation de la méthode eval()
- Utilisation de la méthode ast.literal_eval()
Convertir une chaîne en JSON à l'aide de la méthode json.loads() en Python
Dans cet exemple, nous allons convertir un dictionnaire en objet JSON en utilisant le json.dump() fonction. Ensuite, nous convertirons la représentation sous forme de chaîne d'un objet JSON en dictionnaire en utilisant json.loads() méthode.
Python3
import> json> # initialising json object> ini_string>=> {>'nikhil'>:>1>,>'akash'> :>5>,> >'manjeet'> :>10>,>'akshat'> :>15>}> # printing initial json> ini_string>=> json.dumps(ini_string)> print> (>'initial 1st dictionary'>, ini_string)> print> (>'type of ini_object'>,>type>(ini_string))> # converting string to json> final_dictionary>=> json.loads(ini_string)> # printing final result> print> (>'final dictionary'>,>str>(final_dictionary))> print> (>'type of final_dictionary'>,>type>(final_dictionary))> |
>
>
Sortir:
initial 1st dictionary {'manjeet': 10, 'nikhil': 1, 'akshat': 15, 'akash': 5} type of ini_object final dictionary {'nikhil': 1, 'manjeet': 10, 'akshat': 15, 'akash': 5} type of final_dictionary> Convertir une chaîne en JSON à l'aide de la méthode eval() en Python
La fonction eval() en Python évalue l'expression entrée en tant qu'expression Python et exécute l'expression Python (code) dans le programme.
Exemple
Dans cet exemple, nous convertissons Python chaîne représentation dans un dictionnaire en utilisant Méthode eval() .
Python3
# initialising json object string> ini_string>=> '''{'nikhil': 1, 'akash' : 5,> >'manjeet' : 10, 'akshat' : 15}'''> # printing initial json> print> (>'initial 1st dictionary'>, ini_string)> print> (>'type of ini_object'>,>type>(ini_string))> # converting string to json> final_dictionary>=> eval>(ini_string)> # printing final result> print> (>'final dictionary'>,>str>(final_dictionary))> print> (>'type of final_dictionary'>,>type>(final_dictionary))> |
>
>
Sortir:
initial 1st dictionary {'nikhil': 1, 'akash' : 5, 'manjeet' : 10, 'akshat' : 15} type of ini_object final dictionary {'nikhil': 1, 'manjeet': 10, 'akash': 5, 'akshat': 15} type of final_dictionary> Convertir une chaîne en JSON à l'aide de la méthode ast.literal_eval()
La méthode ast.literal_eval() fait partie du module ast (arbre de syntaxe abstraite) en Python. Cette fonction évalue un nœud d'expression, une chaîne composée d'un littéral, et le convertit en objet dictionnaire Python.
Exemple
Ici, nous utiliserons la méthode ast.literal_eval() du module précédent pour convertir une représentation sous forme de chaîne du dictionnaire en Python. dictionnaire . La fonction ast.literal_eval analyse la chaîne et crée un objet dictionnaire Python avec les mêmes propriétés et valeurs. L'objet dictionnaire résultant a un type de dict. Nous pouvons ensuite accéder aux propriétés de l'objet dictionnaire en utilisant la notation standard d'accès au dictionnaire (par exemple dict_obj[name]).
Python3
import> ast> # initialize the string to be converted> string>=> '{'name': 'John', 'age': 30, 'city': 'New York'}'> # use the ast.literal_eval function to parse the string and create a dictionary object> dict_obj>=> ast.literal_eval(string)> # printing final result> print> (>'Initial string dictionary: '>,string)> print> (>'Final dictionary: '>,dict_obj)> print>(>type>(dict_obj))> |
>
essayez le bloc catch java
>
Sortir:
Initial string dictionary: {'name': 'John', 'age': 30, 'city': 'New York'} Final dictionary: {'name': 'John', 'age': 30, 'city': 'New York'}>