目录
json字符串转python对象
json字符串转dict
json字符串 转list
python对象转json格式字符串
dict转json
list转json
json格式字符串写入文件
从文件读取json格式字符串
json字符串转python对象
基于json.loads完成
json字符串转dict
import json
test_str = '{"name": "ww", "age": 99, "causes": ["A","B"]}'
json1 = json.loads(test_str)
print("json1={}, type={}, len(json1)={}".format(json1, type(json1), len(json1)))
print("json1.age={}".format(json1['age']))
# json1={'name': 'ww', 'age': 99, 'causes': ['A', 'B']}, type=
# json1.age=99
# test_str为正确的json格式
# test_str2 = "{'name': 'ww', 'age': 99, 'causes': ['A','B']}"
# json2 = json.loads(test_str2)
# print("json2={}, type={}".format(json2, type(json2)))
# 转换失败json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
# 注意:test_str2字符串不符合json的格式
json字符串 转list
test_str1 = ' ["A", "B", "C"]'
json2 = json.loads(test_str1)
print("json2={}, type={}, len(json1)={}".format(json2, type(json2), len(json2)))
print("json2[1]={}".format(json2[1]))
# json2=['A', 'B', 'C'], type=, len(json1)=3
# json2[1]=B
python对象转json格式字符串
python对象转json格式字符串
基于json.dumps完成
dict转json
dict1 = {'name': 'ww', 'age': 99, 'causes': ['A',"B"]}
json3 = json.dumps(dict1)
print("json3={}, type={}".format(json3, type(json3)))
# json3={"name": "ww", "age": 99, "causes": ["A", "B"]}, type=
list转json
list1 = ["A", "B", "C"]
json4 = json.dumps(list1)
print("json4={}, type={}".format(json4, type(json4)))
# json4=["A", "B", "C"], type=
json格式字符串写入文件
test_dict = {'name': 'ww', 'age': 99, 'causes': ['A',"B"]}
with open('a.json', 'a', encoding='utf-8') as f0:
json.dump(test_dict, f0)
# 参数1传入需要写入文件的字符串对应的python对象即可,无需手动转换为字符串再写入
从文件读取json格式字符串
with open('a.json', 'r', encoding='utf-8') as f0:
file_data = json.load(f0)
list1 = ["A", "B", "C"]
json4 = json.dumps(list1)
print("json4={}, type={}".format(json4, type(json4)))
# json4=["A", "B", "C"], type=
json格式字符串写入文件
test_dict = {'name': 'ww', 'age': 99, 'causes': ['A',"B"]}
with open('a.json', 'a', encoding='utf-8') as f0:
json.dump(test_dict, f0)
# 参数1传入需要写入文件的字符串对应的python对象即可,无需手动转换为字符串再写入
从文件读取json格式字符串
with open('a.json', 'r', encoding='utf-8') as f0:
file_data = json.load(f0)
with open('a.json', 'r', encoding='utf-8') as f0:
file_data = json.load(f0)
如有帮助,欢迎留下足迹哦!



