转载: https://www.jb51.net/article/140151.htm
import json
name_emb = {'a': '1111', 'b': '2222', 'c': '3333', 'd': '4444'} #写的字典
jsDumps = json.dumps(name_emb)
#将字典转换成str
jsLoads = json.loads(jsDumps) #将str 转换成字典
print(name_emb) print(jsDumps) print(jsLoads) print(type(name_emb)) print(type(jsDumps)) print(type(jsLoads))
{'a': '1111', 'b': '2222', 'c': '3333', 'd': '4444'}
{"a": "1111", "b": "2222", "c": "3333", "d": "4444"}
{'a': '1111', 'b': '2222', 'c': '3333', 'd': '4444'}
<class 'dict'>
<class 'str'>
<class 'dict'>
print("=================================================")
emb_filename = ('emb_json.json') # solution 1 jsObj = json.dumps(name_emb) with open(emb_filename, "w") as f: f.write(jsObj) f.close() # solution 2 json.dump(name_emb, open(emb_filename, "w"))
dump
#将字典 转换为str 并写入文件 {'a': '1111', 'b': '2222', 'c': '3333', 'd': '4444'}
jsObj = json.load(open(emb_filename)) print(jsObj) print(type(jsObj)) for key in jsObj.keys(): print('key: %s value: %s' % (key, jsObj.get(key)))
{'a': '1111', 'b': '2222', 'c': '3333', 'd': '4444'}
<class 'dict'>
key: a value: 1111
key: b value: 2222
key: c value: 3333
key: d value: 4444
load
读取文件中的str 并转换成字典