Python如何读写json数据

Jackey Python 1,623 次浏览 , 没有评论
# 如何读写json数据
import json

l = [1, 2, 'abc', {'name': 'Bob', 'age': 13}]

print(json.dumps(l))

d = {'b': None, 'a': 5, 'c': 'abc'}

print(json.dumps(d))
# 压缩字符串长度,去掉空格
print(json.dumps(d, separators=[',', ':']))

# 对输出的键排序
print(json.dumps(d, sort_keys=True))

# 将json字符串转换为列表
l2 = json.loads('[1, 2, "abc", {"name": "Bob", "age": 13}]')
print(l2[2])
# 将json字符串转换为字典
d2 = json.loads('{"b":null,"a":5,"c":"abc"}')
print(d2['a'])

# load 和 dump 是对文件的读写
with open('demo.json', 'w') as f:
    json.dump(l, f)

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Go