# 引入json包名
import json
# json格式的数据,在Python中jsonObj对应dict,jsonArray 对应List
g_data = {
'name': 'pengjunlee',
'age': 32,
'vip': True,
'address': {'province': 'GuangDong', 'city': 'ShenZhen'}
}
# load 将文件中的json数据转换成Python的数据格式
def test_load(file):
with open(file) as f:
return json.load(f)
# dump 将python的json数据格式写入文件
def test_dump(file):
with open(file, 'w') as f:
json.dump(g_data, f)
# 将python的json数据格式转换为json字符串
def test_dumps(data):
json_str = json.dumps(data)
print(type(json_str))
return json_str
# 读取json字符串,转化后的格式为python中的json数据格式
def test_loads(json_str):
json_data = json.loads(json_str)
if type(json_data) is dict:
print("json_data is dict")
else:
print("json_data is not dict")
def test_main():
# file_name = "test.json"
# # test_dump(file_name)
# json_data = test_load(file_name)
# for key in json_data:
# value = json_data[key]
# print(value)
json_str = test_dumps(g_data)
test_loads(json_str)
if __name__ == '__main__':
test_main()
Python 中json 数据处理
最新推荐文章于 2024-06-24 15:05:02 发布