关于JSON的详细知识,可以参考JSON官网
一个简单的例子:
def json_sosa():
import json
myjson = {
'name': '二蛋',
'age': 27,
'sex': '男',
'family': ['老爸', '老妈', '小妹'],
'cars': {'brand': 'ford','type': '福睿斯'}
}
try:
with open('myini.json', 'w', encoding='utf-8') as myini:
# dump - 将Python对象按照JSON格式序列化到文件中
json.dump(myjson, myini)
# dumps - 将Python对象处理成JSON格式的字符串
_dumps = json.dumps(myjson)
print(_dumps)
with open('myini.json', 'r', encoding='utf-8') as myini:
# load - 将文件中的JSON数据反序列化成对象
_load = json.load(myini)
print(_load)
# loads - 将字符串的内容反序列化成Python对象
_loads = json.loads(r'{"name": "\u4e8c\u491c"}')
print(_loads)
except IOError:
print(IOError.args)
print('OK!!')
json_sosa()
实行结果:
{"name": "\u4e8c\u86cb", "age": 27, "sex": "\u7537", "family": ["\u8001\u7238", "\u8001\u5988", "\u5c0f\u59b9"], "cars": {"brand": "ford", "type": "\u798f\u777f\u65af"}}
{'name': '二蛋', 'age': 27, 'sex': '男', 'family': ['老爸', '老妈', '小妹'], 'cars': {'brand': 'ford', 'type': '福睿斯'}}
{'name': '二䤜'}
OK!!