记事本写入 打开来还是原样
python dict写入 会转成gbk
import json5
addr_1 = r'd:\data\data_1.json5'
addr_2 = r'd:\data\data_2.json5'
addr_3 = r'd:\data\data_3.json5'
data_1 = {
"name": "John",
"age": 30,
"city": "New York"
}
data_2 = {
"//": "这是我的注释",
"//2": "这是我的第二个注释",
"unquoted": '可以使用未引用的键',
"singleQuotes": '可以使用单引号',
"lineBreaks": "可以跨行的字符串\
这是第二行",
"hexadecimal": 0xdecaf,
"leadingDecimalPoint": .8675309, # 可以有前导小数点
"andTrailing": 8675309., # 可以有尾随小数点
"positiveSign": +1, # 可以有正号
"trailingComma": '在对象中可以有尾随逗号',
"andIn": ['数组中也可以',],
}
In [65]:
with open(addr_1, 'w') as f:
json5.dump(data_1, f)
with open(addr_2, 'w') as f:
json5.dump(data_2, f)
In [66]:
with open(addr_1, 'r', encoding='utf-8', errors='ignore') as f:
config_1 = json5.load(f)
print(config_1)
{'name': 'John', 'age': 30, 'city': 'New York'}
In [67]:
with open(addr_2, 'r', encoding='utf-8', errors='ignore') as f:
config_2 = json5.load(f)
print(config_2)
{'//': '这是我的注释', '//2': '这是我的第二个注释', 'unquoted': '可以使用未引用的键', 'singleQuotes': '可以使用单引号', 'lineBreaks': '可以跨行的字符串 这是第二行', 'hexadecimal': 912559, 'leadingDecimalPoint': 0.8675309, 'andTrailing': 8675309.0, 'positiveSign': 1, 'trailingComma': '在对象中可以有尾随逗号', 'andIn': ['数组中也可以']}
In [68]:
# 记事本写入, 默认保存为utf-8
with open(addr_3, 'r', encoding='utf-8', errors='ignore') as f:
config_3 = json5.load(f)
print(config_3)
{'unquoted': '可以使用未引用的键', 'singleQuotes': '可以使用单引号', 'lineBreaks': '可以跨行的字符串 这是第二行', 'hexadecimal': 912559, 'leadingDecimalPoint': 0.8675309, 'andTrailing': 8675309.0, 'positiveSign': 1, 'trailingComma': '在对象中可以有尾随逗号', 'andIn': ['数组中也可以']}