python学习笔记08:json

1. dict与str之间转换

1.1. dict -> str

>>> import json
>>> d0 = {1:'a', 2:{'2k0':'2v0', '2k1':'2v1'}}
>>> s0 = json.dumps(d0) # 将字典转为字符串
>>> s0
'{"1": "a", "2":{"2k0":"2v0", "2k1":"2v1"}}'
>>> type(s0)
<class 'str'>

1.2 str -> dict

>>> d1 = json.loads(s0) # 将字符串转为字典
>>> d1
{1:'a', 2:{'2k0':'2v0', '2k1':'2v1'}}
>>> type(d1)
<class 'dict'>

2. dict与文件间转换

注意,json操作文件时,操作对象是文件句柄,而不是文件本身。

2.1. dict -> fid

>>> with open('d0.json', 'w') as fid:
...     json.dump(d0, fid, indent=4) # 将字典写入到文件中
...
>>> for line in open('d0.json', 'r').readlines():
...     print(line)
...
{
"1": "a",
"2": {
"2k0":"2v0",
"2k1":"2v1"
}
}

或者在dump参数中直接open文件

json.dump(d0, open('d0.json', 'w'), indent=4)

2.2. fid -> dict

>>> with open('d0.json', 'r') as fid:
...     d1 = json.load(fid) # 将json文件中加载到字典
...
>>> d1
{1:'a', 2:{'2k0':'2v0', '2k1':'2v1'}}

或者在load参数中直接open文件

d1 = json.load(open('d0.json', 'r'))

2.3 dict与.gz压缩文件

import json
import gzip

d = dict()
d['a'] = dict()
d['a']['0'] = 'a0'
d['a']['1'] = 'a1'

d['b'] = 'b'

#dict -> file.gz
fout = gzip.open('d.json.gz', 'wb')
fout.write(json.dumps(d, indent=4).encode())
fout.close()

#file.gz -> dict
dl = json.load(gzip.open('d.json.gz', 'rt'))
print(dl['a']['0'])
print(dl['a']['1'])
print(dl['b'])

posted @ 2020-07-03 10:50  编程驴子  阅读(104)  评论(0编辑  收藏  举报