Python. Dict - Str - Json (Словарь - Строка - JSON)
Python. Dict - Str - Json (Словарь - Строка - JSON)
Перевод разных форматов:
import json
# создадим словарь (dict)
dict1 = {'one':1, 'two':2, 'three': {'three.1': 3.1, 'three.2': 3.2 }}
# dict -> string
str_ = str(dict1)
print( 'str1 -', str_ )
# str1 - {'one': 1, 'two': 2, 'three': {'three.1': 3.1, 'three.2': 3.2}}
# string -> dict
dict2 = eval(str_)
print( 'dict2==dict1 -', dict2==dict1 )
# dict2==dict1 - True
# dict -> json
json1 = json.dumps(dict1)
print( 'json1 -', json1 )
#json1 - {"one": 1, "two": 2, "three": {"three.1": 3.1, "three.2": 3.2}}
# dict -> json с форматированием
json1_ = json.dumps( dict1, indent=3, separators=(',',': ') )
print( 'json.dumps( dict1 .. ) \n', json1_ )
# json.dumps( dict1 .. ) -
# {
# "one": 1,
# "two": 2,
# "three": {
# "three.1": 3.1,
# "three.2": 3.2
# }
# }
# json -> dict
dict3 = json.loads(json1)
print( 'dict3 -', dict3 )
#dict3 - {'one': 1, 'two': 2, 'three': {'three.1': 3.1, 'three.2': 3.2}}
# json -> dict -> json с форматированием
json1_ = json.dumps( json.loads(json1), indent=3, separators=(',',': ') )
print( 'json1_ -', json1_ )
#json1_ - {
# "one": 1,
# "two": 2,
# "three": {
# "three.1": 3.1,
# "three.2": 3.2
# }
#}
Комментарии
Отправить комментарий