JSON是 JavaScript Object Notation的简称,是一种轻量的数据表示方法。JSON 能够将 JavaScript 对象中表示的一组数据转换为字符串,然后就能够在函数之间轻松地传递这个字符串,或者在异步应用程序中将字符串从 Web 客户机传递给server端程序。
json.dumps()
和json.loads()
是json格式处理函数;json.dump()
和json.load()
主要用来读写json文件函数。
json.dumps()将Python对象编码成json字符串
import json
# json.dumps()函数的使用,将字典转化为字符串
dic = {"age": "12"}
json_info = json.dumps(dic)
print("dic的类型:"+str(type(dic)))
print("通过json.dumps()函数处理:")
print("json_info的类型:"+str(type(json_info)))
运行结果:
json.loads()将已编码的 json字符串解码为 Python 对象
import json
# json.loads函数的使用,将字符串转化为字典
json_info = '{"age": "12"}'
dic = json.loads(json_info)
print("json_info的类型:"+str(type(json_info)))
print("通过json.loads()函数处理:")
print("dic的类型:"+str(type(dic)))
运行结果:
json.dump()将Python内置类型序列化为json对象后写入文件
import json
# json.dump()函数的使用,将json信息写进文件
json_info = "{'age': '12'}"
with open('newfile.json','w',encoding='utf-8') as f:
json.dump(json_info,f)
运行结果:
json.load()读取文件中json形式的字符串元素转化为Python类型
import json
# json.load()函数的使用,将读取json信息
with open('newfile.json','r',encoding='utf-8') as f:
info = json.load(f)
print(info)
运行结果:
读取多行的json文件
json | 文件读写open()、with
如果直接使用:
with open("Sarcasm.json", 'r') as f:
datastore = json.load(f)
或者(先读取为Python中str类型,再使用json.load()函数转化为json格式):
with open("Sarcasm.json", 'r') as f:
line = f.read()
dic = json.loads(line)
则会抛出异常:Extra data: line 2 column 1 (char 208)。表示数据错误,数据太多,因为json只能读取一个文档对象。有两个解决办法:
方法一.逐行转换为Python对象
l=[]
with open("Sarcasm.json", 'r') as f:
for line in f.readlines():
item = json.loads(line)
l.append(item)
print(l[0])
print(type(l[0]))
输出:
方法二.保存数据源的时候,格式写为一个对象
数据保存为如下格式(这里保存为一个列表,也可以保存为一个字典):
读取代码:
with open("Sarcasm.json", 'r') as f:
dic = json.load(f)
Python数据类型与json数据类型的映射关系
Python | json |
---|---|
dict | object |
list, tuple | array |
str, unicode | string |
int, long, float | number |
True | true |
False | false |
None | null |
Python中的json操作
json读取数据:ValueError: Extra data: line 77 column 2 - line 16485 column 1 (char 1159 - 227243)