Python的json模块:json.dumps()/ json.loads()与json.dump()/ json.load()

  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数据类型的映射关系

Pythonjson
dictobject
list, tuplearray
str, unicodestring
int, long, floatnumber
Truetrue
Falsefalse
Nonenull

Python中的json操作
json读取数据:ValueError: Extra data: line 77 column 2 - line 16485 column 1 (char 1159 - 227243)

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值