import json
def encode(dic):
# Marche aussi avec des listes, des listes et dictionnaires imbriqués, etc ...
return json.dumps(dic)
def encode_pretty(dic):
return json.dumps(dic, sort_keys=True, indent=4, separators=(',', ': '))
def encode_compact(dic):
return json.dumps(dic, separators=(',',':'))
def decode(j):
return json.loads(j)
mydictionary = {"key" : "value", "anotherkey" : "anothervalue"}
j = encode(mydictionary)
print(j)
# > {"key": "value", "anotherkey": "anothervalue"}
print(type(j))
# > <class 'str'>
compact = encode_compact(mydictionary)
print(compact)
# > {"key":"value","anotherkey":"anothervalue"}
pretty = encode_pretty(mydictionary)
print(pretty)
# > {
# "anotherkey": "anothervalue",
# "key": "value"
# }
dic = decode(j)
print(dic)
# > {'key': 'value', 'anotherkey': 'anothervalue'}
print(type(dic))
# > <class 'dict'>
print(dic == mydictionary)
# > True