1. 用json读取字符串文件

import json  # 读取数据,我们的数据为json格式的

str='''[{"name":"kingsan",
        "age":'23'},
        {"name":"xiaolan",
        "age":"23"}]
'''
print(type(str))
data = json.loads(str)
print(data)
print(type(data))
JSONDecodeError: Expecting value: line 2 column 15 (char 34)

运行时发现错误:

解决办法:
原来数据格式里string类型的数据要用双引号,而不是单引号。

修改之后:

import json
str='''[{"name":"kingsan",
        "age":"23"},
        {"name":"xiaolan",
        "age":"23"}]
'''
print(type(str))
data = json.loads(str)
print(data)
print(type(data))
<class 'str'>
[{'name': 'kingsan', 'age': '23'}, {'name': 'xiaolan', 'age': '23'}]
<class 'list'>

参考文章(json.decoder.JSONDecodeError: Expecting value错误的解决方法

2. 用json读取文本文件

大概的形式为:

import json
with open('data.json','r') as file:
    str = file.read()
    data = json.loads(str)
    print(data)

具体案例:

import json
data =[{
'name':'kingsan',
'age':'23'
}]

with open('data.json','w') as file:
	file.write(json.dumps(data))
    
with open('data.json', "r") as f:
    for idx, col in enumerate(f):
        print(idx)   # 显示的行标签
        print(col)   # 显示某一行的内容

把字典写入json文件(参考

import json
data ={
      "grade1": {'name':'kingsan','age':'23'},
      "grade2": {"name": "xiaoliu","age":"24"},
      "grade3": {"name":"xiaowang","age":"22"}}


with open('data.json','w') as file:   # 写文件
	file.write(json.dumps(data))
    
with open('data.json', "r") as f:     # 读文件
    for idx, line in enumerate(f):
#         pass
        print(idx)
        print(line)

print(type(line))

0
{"grade1": {"name": "kingsan", "age": "23"}, "grade2": {"name": "xiaoliu", "age": "24"}, "grade3": {"name": "xiaowang", "age": "22"}}
str

3. json.dump()写入、json.load()读取

使用json.dump() 把数据写入到指定的文件名中

使用方法:

json.dump( 数据 ,  文件名) 
import json
number = [1,2,3,5]
file_name = 'number.json' #通过扩展名指定文件存储的数据为json格式
with open(file_name,'w') as file_object:
    json.dump(number,file_object)

使用 json.load() 从已经写入的文件中读取数据:

使用方法:

变量名 = json.load(文件名)
with open(filename,'r') as file_object:
    contents = json.load(file_object)
print(contents)

参考文章(使用json.dump()和json.load()

4. json.dumps()写入、json.loads()读取

json.dumps() 将python对象格式化成json字符(说了等于白说)
那么怎么理解:

import json

str={'article':'hello','  tag':'美女'}
# 将python对象格式化成json字符串
encoded_json=json.dumps(str,ensure_ascii=False)
print(encoded_json,type(encoded_json))

# 将json字符串解码成python对象
decode_json=json.loads(encoded_json)
print(decode_json,type(decode_json))

注意:
json.loads() 读取的是字符串文件,并且文件中的字符变量变量需要加双引号

如何把多个字典写入到一个json文件中,且每个字典占一个位置

dic1 = {"name":"abc", "age":"123"}
dic2 = {"name":"efg", "age":"456"}
dic_full = [dic1, dic2]

# 写成 .json 文件
with open("df.json", "w") as file:
    json.dump(dic_full, file)

# 读取文件
with open("df.json", "r") as f:
    for idx, line in enumerate(f):
#         print(idx)
#         print(line)
        d = json.loads(line)
    print(d)
    print(type(d))
[{'name': 'abc', 'age': '123'}, {'name': 'efg', 'age': '456'}]
<class 'list'>

读取具体项目:

for i, j in enumerate(d):
    print(i, type(i))
    print(j, type(j))
0 <class 'int'>
{'name': 'abc', 'age': '123'} <class 'dict'>
1 <class 'int'>
{'name': 'efg', 'age': '456'} <class 'dict'>

参考文章:
python对json支持——如何给json文件写入多个字典并读出多个字典

四者相互比较

参考文章:
json中json.loads()和json.dumps()的区别

dump 和 dumps 都实现了序列化
load 和 loads 都实现反序列化

json.loads() 是将字符串传化为字典
json.dumps () 是将字典转化为字符串
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐