• PYTHON > fichiers et données json

      Avant toute chose, il faut importer la librairie json:

       

      import json

      OBJET JSON

      json.loads(var) # lire une chaine de type strings

      Lire

      a = '{"nom": "toto", "age": 69}'
      A = json.loads(a) # deserializes into dict and returns dict.print("JSON string = ", y)
      for D in A:
         print(D)

      Ajouter un élément

      dic = '{}'
      dic['liste'].append({'nom':'toto','age':69})

       

      dic = '{"liste":[]}'
      dic['liste'].append({'nom':'toto','age':69})

      FICHIER JSON

      Importer / Lire

      S = unicodedata.normalize(‘NFKD’, P0).encode(‘ASCII’, ‘ignore’).decode(‘utf-8′).lower()

       

      with open(fichier.json, 'r+', encoding='utf-8') as f: # Ouvre le fichier json
          data = json.load(f) # retourne l'objet JSON en tant que dictionnaire
          for D in data: # Parcours le tableau de données (on peut dire aussi for f in data['liste'])
              print(D)
              print(D['toto'])

      Update / Modifier

      with open("fichier.json", "r", encoding='utf-8') as f:
          json_o = json.load(f)
      
      json_o["toto"] = 100. # changer la valeur
      with open("fichier.json", "w", encoding='utf-8') as f:
          json.dump(json_o, f)

      Append / Ajouter

      PRINCIPE = Importer le fichier > transformer le json en objet > ajouter dans l’objet > convertir l’objet en json > écrire le json dans le fichier

      json.loads(): json.loads(json_string) To parse the JSON string. It returns the python dictionary object.

      json.dumps(): json.dumps(object) To convert Python object into JSON string. It takes Python Object as the parameter. It returns the JSON string.

      update(): This method updates the dictionary with elements from another dictionary object or from an iterable key/value pair. dict.update([other]) Takes another dictionary or an iterable key/value pair.

       

      Example 1: Updating a JSON string.

      x = '{"nom":"toto", "age":69}'
      y = {"ville":"totocity"} # élément à ajouter
      z = json.loads(x) # parsing JSON string
      z.update(y) # appending the data
      print(json.dumps(z))
      {"nom":"toto", "age":69, "ville":"totocity"}

       

      We want to add another JSON data after emp_details. Below is the implementation.

      # function to add to JSON
      def write_json(new_data, filename='data.json'):
          with open(filename,'r+') as file:
              # First we load existing data into a dict.
              file_data = json.load(file)
              # Join new_data with file_data inside emp_details
              file_data["emp_details"].append(new_data)
      # Sets file's current position at offset.
      file.seek(0)
      # convert back to json.
      json.dump(file_data, file, indent = 4)
      # python object to be appended
      y = {"emp_name":"Nikhil",
      "email": "nikhil@geeksforgeeks.org",
      "job_profile": "Full Time"
      }
      write_json(y)

       

      python-append-json

       

 

Aucun commentaire

 

Laissez un commentaire