JSON – JavaScript Object Notation

Serialization wandelt Daten ins JSON format (z.B. Liste in Python –> JSON).

Deserialization wandelt JSON zu Objekten (z.B. JSON zu einer Liste in Python).

dump() schreibt die Daten in ein file-like object (also eine Datei).

dumps() schreibt die Daten in einen String.

import json
liste = ['Peter', 'löst','Probleme', 'gern', 'mit', 'der','Programmiersprache','Python']
with open('result.json', 'w') as fp:
    json.dump(liste, fp)
with open('result.json', 'r') as fp:
    print(fp.readlines())
['["Peter", "l\u00f6st", "Probleme", "gern", "mit", "der", "Programmiersprache", "Python"]']
json_str = json.dumps(liste, indent=4)
print(json_str)
[
    "Peter",
    "lu00f6st",
    "Probleme",
    "gern",
    "mit",
    "der",
    "Programmiersprache",
    "Python"
]

Unterschiedliche Typen in Python und JavaScript

Python JSON
dict object
list, tuple array
str string
int, long, float number
True true
False false
None null
json_string = json.dumps([1, 2, 3, "a", "b", "c"])
print(json_string)
[1, 2, 3, "a", "b", "c"]

load() lesen der Daten von einem file-like object (also einer Datei).

loads() lesen der Daten aus einem String.

Pickle

https://docs.python.org/3.7/library/pickle.html

WARNUNG:

The pickle module is not secure against erroneous or maliciously constructed data.

Never unpickle data received from an untrusted or unauthenticated source.

# nicht mehr notwendig: import cPickle as pickle
# es reicht der folgende Import:

import pickle

pickled_string = pickle.dumps([1, 2, 3, "a", "b", "c"])
print(pickle.loads(pickled_string))
[1, 2, 3, 'a', 'b', 'c']
---------------------------------------------------------------------------

ModuleNotFoundError                       Traceback (most recent call last)

<ipython-input-3-400cc400590d> in <module>
----> 1 import cPickle as pickle


ModuleNotFoundError: No module named 'cPickle'