json操作
https://docs.python.org/3/library/json.html
# 该module总是产生str对象,而不是bytes对象。
import json
""" Encoding """
# json.dump(obj, fp, ......): 将obj作为一个JSON-formatted stream序列化到fp(a .write()-supporting file-like object)。 因为json模块产生的是str对象,所以fp.write() must support str input.
from io import StringIO
io = StringIO()
json.dump(['streaming API'], io)
io.getvalue() # return: '["streaming API"]'
# json.dumps(obj, *, .......): 将obj作为一个JSON-formatted str进行序列化
json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':'))
json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
""" Decoding """
# json.load(fp, *, ......): 解序列化fp (a .read()-supporting text file or binary file containing a JSON document) 到一个Python对象
from io import StringIO
io = StringIO('["streaming API"]')
json.load(io)
with open(filepath, 'r') as jsonfile:
jsonobj = json.load(jsonfile)
# json.loads(s, ......): Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object
json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
import chardet
# 首先二进制方式打开文件
with open(absPath, 'rb') as frb:
# 检测编码方式
cur_encoding = chardet.detect(frb.read())['encoding']
# 指定文件编码方式
with open(absPath, 'r', encoding=cur_encoding) as fr:
Content = fr.read()