Industrielle Fertigung
Industrielles Internet der Dinge | Industrielle Materialien | Gerätewartung und Reparatur | Industrielle Programmierung |
home  MfgRobots >> Industrielle Fertigung >  >> Industrial programming >> Python

Python JSON:Codieren (Dumps), Decodieren (Laden) und JSON-Datei lesen

Was ist JSON in Python?

JSON in Python ist ein von JavaScript inspiriertes Standardformat für den Datenaustausch und die Datenübertragung als Textformat über ein Netzwerk. Im Allgemeinen liegt JSON im String- oder Textformat vor. Es kann von APIs und Datenbanken verwendet werden und stellt Objekte als Name/Wert-Paare dar. JSON steht für JavaScript Object Notation.

Python-JSON-Syntax:

JSON wird als Schlüssel-Wert-Paar geschrieben.

{
        "Key":  "Value",
        "Key":  "Value",
} 

JSON ist sehr ähnlich zu Python-Wörterbuch. Python unterstützt JSON und hat eine eingebaute Bibliothek als JSON.

JSON-Bibliothek in Python

Marschall ‘ und ‘Gurke’ externe Module von Python pflegen eine Version von JSON Python-Bibliothek. Wenn Sie mit JSON in Python arbeiten, um JSON-bezogene Vorgänge wie Codierung und Decodierung auszuführen, müssen Sie zuerst importieren JSON-Bibliothek und dafür in Ihrer .py Datei,

import json

Die folgenden Methoden sind im JSON-Python-Modul

verfügbar
Methode Beschreibung
dumps() Kodierung in JSON-Objekte
dump() kodierter String in Datei schreiben
lädt() Entschlüsseln Sie die JSON-Zeichenfolge
Laden() Decodieren, während JSON-Datei gelesen wird

Python zu JSON (Codierung)

Die JSON Library of Python führt standardmäßig die folgende Übersetzung von Python-Objekten in JSON-Objekte durch

Python JSON
dict Objekt
Liste Array
unicode Zeichenfolge
Zahl – int, lang Nummer – int
schwimmen Zahl – echt
Richtig Richtig
Falsch Falsch
Keine Null

Das Konvertieren von Python-Daten in JSON wird als Codierungsvorgang bezeichnet. Die Kodierung erfolgt mit Hilfe der JSON-Bibliotheksmethode – dumps()

JSON-Dumps() in Python

json.dumps() in Python ist eine Methode, die Dictionary-Objekte von Python in das JSON-String-Datenformat konvertiert. Es ist nützlich, wenn die Objekte für Operationen wie Parsen, Drucken usw. im String-Format vorliegen müssen.

Lassen Sie uns nun unser erstes json.dumps-Kodierungsbeispiel mit Python durchführen:

import json

x = {
  "name": "Ken",
  "age": 45,
  "married": True,
  "children": ("Alice","Bob"),
  "pets": ['Dog'],
  "cars": [
    {"model": "Audi A1", "mpg": 15.1},
    {"model": "Zeep Compass", "mpg": 18.1}
  ]
}
# sorting result in asscending order by keys:
sorted_string = json.dumps(x, indent=4, sort_keys=True)
print(sorted_string)

Ausgabe:

{"person": {"name": "Kenn", "sex": "male", "age": 28}})

Sehen wir uns ein Beispiel dafür an, wie Python JSON in eine Datei schreibt, um eine JSON-Datei des Wörterbuchs mit derselben Funktion dump() zu erstellen

# here we create new data_file.json file with write mode using file i/o operation 
with open('json_file.json', "w") as file_write:
# write json data into file
json.dump(person_data, file_write)

Ausgabe:

Nichts zu zeigen … In Ihrem System wird json_file.json erstellt. Sie können diese Datei überprüfen, wie im folgenden Python-Beispiel zum Schreiben von JSON in eine Datei gezeigt.

JSON zu Python (Decodierung)

Die Dekodierung von JSON-Strings erfolgt mit Hilfe der eingebauten Methode json.loads() &json.load() der JSON-Bibliothek in Python. Diese Übersetzungstabelle zeigt ein Beispiel für JSON-Objekte in Python-Objekte, die hilfreich sind, um die Decodierung von JSON-Strings in Python durchzuführen.

JSON Python
Objekt diktieren
Array Liste
Zeichenfolge unicode
Nummer – int Zahl – int, lang
Zahl – echt schwimmen
Richtig Richtig
Falsch Falsch
Null Keine

Sehen wir uns ein einfaches Parse-JSON-Python-Beispiel für die Dekodierung mit Hilfe von json.loads an Funktion,

import json  # json library imported
# json data string
person_data = '{  "person":  { "name":  "Kenn",  "sex":  "male",  "age":  28}}'
# Decoding or converting JSON format in dictionary using loads()
dict_obj = json.loads(person_data)
print(dict_obj)
# check type of dict_obj
print("Type of dict_obj", type(dict_obj))
# get human object details
print("Person......",  dict_obj.get('person'))

Ausgabe:

{'person': {'name': 'Kenn', 'sex': 'male', 'age': 28}}
Type of dict_obj <class 'dict'>
Person...... {'name': 'John', 'sex': 'male'}

JSON-Datei dekodieren oder JSON-Datei in Python analysieren

Jetzt lernen wir, wie man JSON-Dateien in Python mit dem Python-Parse-JSON-Beispiel liest:

HINWEIS: Die Dekodierung der JSON-Datei ist ein Vorgang im Zusammenhang mit der Eingabe/Ausgabe von Dateien (E/A). Die JSON-Datei muss auf Ihrem System am angegebenen Speicherort vorhanden sein, den Sie in Ihrem Programm angeben.

Python liest JSON-Datei Beispiel:

import json
#File I/O Open function for read data from JSON File
with open('X:/json_file.json') as file_object:
        # store file data in object
        data = json.load(file_object)
print(data)

Hier Daten ist ein Dictionary-Objekt von Python, wie im obigen Python-Beispiel zum Lesen der JSON-Datei gezeigt.

Ausgabe:

{'person': {'name': 'Kenn', 'sex': 'male', 'age': 28}}

Kompakte Kodierung in Python

Wenn Sie die Größe Ihrer JSON-Datei reduzieren müssen, können Sie die kompakte Codierung in Python verwenden.

Beispiel,

import json
# Create a List that contains dictionary
lst = ['a', 'b', 'c',{'4': 5, '6': 7}]
# separator used for compact representation of JSON.
# Use of ',' to identify list items
# Use of ':' to identify key and value in dictionary
compact_obj = json.dumps(lst, separators=(',', ':'))
print(compact_obj)

Ausgabe:

'["a", "b", "c", {"4": 5, "6": 7}]'

** Here output of JSON is represented in a single line which is the most compact representation by removing the space character from compact_obj **

JSON-Code formatieren (schöner Druck)

Beispiel:

import json
dic = { 'a': 4, 'b': 5 }
''' To format the code use of indent and 4 shows number of space and use of separator is not necessary but standard way to write code of particular function. '''
formatted_obj = json.dumps(dic, indent=4, separators=(',', ': '))
print(formatted_obj)

Ausgabe:

{
   "a" : 4,
   "b" : 5
}

Um dies besser zu verstehen, ändern Sie den Einzug in 40 und beobachten Sie die Ausgabe-

Bestellen des JSON-Codes:

sort_keys -Attribut im Argument der Python-Dumps-Funktion sortiert den Schlüssel in JSON in aufsteigender Reihenfolge. Das sort_keys-Argument ist ein boolesches Attribut. Wenn es wahr ist, ist Sortieren erlaubt, sonst nicht. Sehen wir uns das Beispiel für die Sortierung von Python-String nach JSON an.

Beispiel,

import json

x = {
  "name": "Ken",
  "age": 45,
  "married": True,
  "children": ("Alice", "Bob"),
  "pets": [ 'Dog' ],
  "cars": [
    {"model": "Audi A1", "mpg": 15.1},
    {"model": "Zeep Compass", "mpg": 18.1}
  	],
}
# sorting result in asscending order by keys:
sorted_string = json.dumps(x, indent=4, sort_keys=True)
print(sorted_string)

Ausgabe:

{
    "age": 45,
    "cars": [ {
        "model": "Audi A1", 
        "mpg": 15.1
    },
    {
        "model": "Zeep Compass", 
        "mpg": 18.1
    }
    ],
    "children": [ "Alice",
		  "Bob"
	],
    "married": true,
    "name": "Ken",
    "pets": [ 
		"Dog"
	]
}

Wie Sie das Schlüsselalter beachten können, sind Autos, Kinder usw. in aufsteigender Reihenfolge angeordnet.

Komplexe Objektkodierung von Python

Ein komplexes Objekt besteht aus zwei verschiedenen Teilen, nämlich

  1. Realteil
  2. Imaginärteil

Beispiel:3 +2i

Bevor Sie ein komplexes Objekt codieren, müssen Sie überprüfen, ob eine Variable komplex ist oder nicht. Sie müssen eine Funktion erstellen, die den in einer Variablen gespeicherten Wert überprüft, indem sie eine Instanzmethode verwendet.

Lassen Sie uns die spezifische Funktion erstellen, um zu prüfen, ob das Objekt komplex oder für die Codierung geeignet ist.

import json

# create function to check instance is complex or not
def complex_encode(object):
    # check using isinstance method
    if isinstance(object, complex):
        return [object.real, object.imag]
    # raised error using exception handling if object is not complex
    raise TypeError(repr(object) + " is not JSON serialized")


# perform json encoding by passing parameter
complex_obj = json.dumps(4 + 5j, default=complex_encode)
print(complex_obj)

Ausgabe:

'[4.0, 5.0]'

Komplexe JSON-Objektdekodierung in Python

Um ein komplexes Objekt in JSON zu decodieren, verwenden Sie einen object_hook-Parameter, der überprüft, ob die JSON-Zeichenfolge das komplexe Objekt enthält oder nicht. Lassen Sie uns mit String zu JSON Python Beispiel verstehen,

import json
  # function check JSON string contains complex object
  def is_complex(objct):
    if '__complex__' in objct:
      return complex(objct['real'], objct['img'])
    return objct
  
  # use of json loads method with object_hook for check object complex or not
  complex_object =json.loads('{"__complex__": true, "real": 4, "img": 5}', object_hook = is_complex)
  #here we not passed complex object so it's convert into dictionary
  simple_object =json.loads('{"real": 6, "img": 7}', object_hook = is_complex)
  print("Complex_object......",complex_object)
  print("Without_complex_object......",simple_object)

Ausgabe:

Complex_object...... (4+5j)
Without_complex_object...... {'real': 6, 'img': 7}

Überblick über die JSON-Serialisierungsklasse JSONEncoder

Die JSONEncoder-Klasse wird für die Serialisierung eines beliebigen Python-Objekts während der Codierung verwendet. Es enthält drei verschiedene Kodierungsmethoden, die

Mit Hilfe der encode()-Methode der JSONEncoder-Klasse können wir auch jedes Python-Objekt codieren, wie im folgenden Python-JSON-Encoder-Beispiel gezeigt.

# import JSONEncoder class from json
from json.encoder import JSONEncoder
colour_dict = { "colour": ["red", "yellow", "green" ]}
# directly called encode method of JSON
JSONEncoder().encode(colour_dict)

Ausgabe:

'{"colour": ["red", "yellow", "green"]}'

Überblick über die JSON-Deserialisierungsklasse JSONDecoder

Die JSONDecoder-Klasse wird für die Deserialisierung eines beliebigen Python-Objekts während der Dekodierung verwendet. Es enthält drei verschiedene Dekodierungsmethoden, die

Mit Hilfe der decode()-Methode der JSONDecoder-Klasse können wir auch JSON-Strings decodieren, wie im folgenden Python-JSON-Decoder-Beispiel gezeigt.

import json
# import JSONDecoder class from json
from json.decoder import JSONDecoder
colour_string = '{ "colour": ["red", "yellow"]}'
# directly called decode method of JSON
JSONDecoder().decode(colour_string)

Ausgabe:

{'colour': ['red', 'yellow']}

Entschlüsselung von JSON-Daten aus URL:Beispiel aus der Praxis

Wir werden Daten von CityBike NYC (Bike Sharing System) von der angegebenen URL (https://feeds.citibikenyc.com/stations/stations.json) abrufen und in das Wörterbuchformat konvertieren.

Python lädt JSON aus Datei Beispiel:

HINWEIS:- Stellen Sie sicher, dass die Anforderungsbibliothek bereits in Ihrem Python installiert ist. Wenn nicht, öffnen Sie Terminal oder CMD und geben Sie

ein
import json
import requests

# get JSON string data from CityBike NYC using web requests library
json_response= requests.get("https://feeds.citibikenyc.com/stations/stations.json")
# check type of json_response object
print(type(json_response.text))
# load data in loads() function of json library
bike_dict = json.loads(json_response.text)
#check type of news_dict
print(type(bike_dict))
# now get stationBeanList key data from dict
print(bike_dict['stationBeanList'][0]) 

Ausgabe:

<class 'str'>
<class 'dict'>
{
	'id': 487,
 	'stationName': 'E 20 St & FDR Drive',
	'availableDocks': 24,
	'totalDocks': 34,
	'latitude': 40.73314259,
	'longitude': -73.97573881,
	'statusValue': 'In Service',
	'statusKey': 1,
	'availableBikes': 9,
	'stAddress1': 'E 20 St & FDR Drive',
	'stAddress2': '',
	'city': '',
	'postalCode': '',
	'location': '', 
	'altitude': '', 
	'testStation': False, 
	'lastCommunicationTime': '2018-12-11 10:59:09 PM', 'landMark': ''
}

Ausnahmen im Zusammenhang mit der JSON-Bibliothek in Python:

Python lädt JSON aus Datei Beispiel:

import json
#File I/O Open function for read data from JSON File
data = {} #Define Empty Dictionary Object
try:
        with open('json_file_name.json') as file_object:
                data = json.load(file_object)
except ValueError:
     print("Bad JSON file format,  Change JSON File")

Unendliche und NaN-Zahlen in Python

Das JSON Data Interchange Format (RFC – Request For Comments) lässt keinen unendlichen oder Nan-Wert zu, aber es gibt keine Einschränkung in der Python-JSON-Bibliothek, um Operationen im Zusammenhang mit unendlichen und Nan-Werten durchzuführen. Wenn JSON den Datentyp INFINITE und Nan erhält, wird es in Literal umgewandelt.

Beispiel,

import json
# pass float Infinite value
infinite_json = json.dumps(float('inf'))
# check infinite json type
print(infinite_json)
print(type(infinite_json))
json_nan = json.dumps(float('nan'))
print(json_nan)
# pass json_string as Infinity
infinite = json.loads('Infinity')
print(infinite)
# check type of Infinity
print(type(infinite))

Ausgabe:

Infinity
<class 'str'>
NaN
inf
<class 'float'>	

Wiederholter Schlüssel im JSON-String

RFC gibt an, dass der Schlüsselname in einem JSON-Objekt eindeutig sein sollte, aber es ist nicht obligatorisch. Die Python-JSON-Bibliothek löst keine Ausnahme von wiederholten Objekten in JSON aus. Es ignoriert alle wiederholten Schlüssel-Wert-Paare und berücksichtigt nur das letzte Schlüssel-Wert-Paar unter ihnen.

import json
repeat_pair = '{"a":  1, "a":  2, "a":  3}'
json.loads(repeat_pair)

Ausgabe:

{'a': 3}

CLI (Befehlszeilenschnittstelle) mit JSON in Python

json.tool stellt die Befehlszeilenschnittstelle zum Validieren der JSON-Pretty-Print-Syntax bereit. Sehen wir uns ein Beispiel für CLI

an

$ echo '{"name" : "Kings Authur" }' | python3 -m json.tool

Ausgabe:

{
    "name": " Kings Authur "
}

Vorteile von JSON in Python

Einschränkungen der Implementierung von JSON in Python

Python-JSON-Spickzettel

Python-JSON-Funktion Beschreibung
json.dumps(person_data) JSON-Objekt erstellen
json.dump(person_data, file_write) JSON-Datei mit Datei-I/O von Python erstellen
compact_obj =json.dumps(data, separators=(‘,’,’:’)) Komprimieren Sie das JSON-Objekt, indem Sie das Leerzeichen aus dem JSON-Objekt mithilfe des Trennzeichens entfernen
formatted_obj =json.dumps(dic, indent=4, separators=(‘,’, ‘:‘)) JSON-Code mit Einzug formatieren
sorted_string =json.dumps(x, indent=4, sort_keys=True) JSON-Objektschlüssel in alphabetischer Reihenfolge sortieren
complex_obj =json.dumps(4 + 5j, default=complex_encode) Python Complex Object-Codierung in JSON
JSONEncoder().encode(colour_dict) Verwendung der JSONEncoder-Klasse für die Serialisierung
json.loads(data_string) Decodierung von JSON-String im Python-Wörterbuch mit der Funktion json.loads()
json.loads(‘{„__complex__“:true, „real“:4, „img“:5}’, object_hook =is_complex) Decodierung eines komplexen JSON-Objekts in Python
JSONDecoder().decode(Farbzeichenfolge) Verwendung der Dekodierung von JSON zu Python mit Deserialisierung

Python

  1. Python-Datentypen
  2. Python-Operatoren
  3. Python-While-Schleife
  4. Python-pass-Anweisung
  5. Python-Funktionsargumente
  6. Python-Wörterbuch
  7. Python-Datei-I/O
  8. Java BufferedReader:Lesen von Dateien in Java mit Beispiel
  9. Python-Prüfung, ob Datei vorhanden ist | So prüfen Sie, ob ein Verzeichnis in Python existiert
  10. Python - Datei-I/O