python处理json格式数据

一、背景

json格式是一种轻量级的数据交换格式,结构上为键值对的形式,常见于爬虫和数据分析应用领域。Python中有json和pickle两个库可以处理json格式。
json和pickle库提供了四种处理方法:dumps,dump,loads,load

json数据处理类型

  • 序列化:将python的数据转换为json格式的字符串
  • 反序列化:将json格式的字符串转换为python类型

1.序列化

1.1 json.dump()

常用于对文件的读写操作,该方法将字典类型数据写入json格式文件。

import json
student = {'name':'Job', 'age':'26'}
with open('student_list.json', 'w+') as file:
	json.dump(student, file)	

1.2 to_json()

效果同上。

import pandas as pd
student_list= [['Job', '26'],['MIke', '23']]

# 整合成dataframe格式
df = pd.Dataframe(student_list, columns=['name', 'age'])
with open('student_list.json', 'w+') as file:
	df.to_json(file, orient='index')

1.3json.dumps()

与上述json.dump()的区别是:json.dump()聚焦于数据本身类型的转换,对数据的操作。

import json
student = {'name':'Job', 'age':'26'}
student_json = json.dumps(student)
print(type(student_json))

2.反序列化

2.1 json.load()

主要处理json格式文件,将json格式数据转换为python可读的字典类型,可对其中的键值对进行数据和格式的修改。

import json

with open('student_list.json', 'r') as json_file:
	students = json.load(json_file)

print(students)
print(type(students)) # dict类型
print(studnets['name'])

2.2 read_json()

效果同上。

import pandas as pd

with open('student_list.json', 'r') as json_file:
	df_students = pd.read_json(json_file, orient='index')
print(df_students.head())

2.3 json.loads()

与json.load()的主要区别是:json.laods()主要是对json编码的字符串进行数据类型的转换。

import json

students = json.loads(studnet_json)
print(type(students)) # 将json编码的字符串转换为python的字典类型
print(students['age']) 
  • 3
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值