Python中处理JSON文件(json和pandas方式)
JSON(Java Script Object Notation)是一种流行的文件格式,主要用于在web应用程序中存储和传输数据。
学习如何读取和写入JSON;
JSON结构看起来和Python中的字典非常类似。
需要注意的是,JSON格式通常是由 key: value 结对组成,其中key是字符串形式,value是字符串、数字、布尔值、数组、对象或null;
在Python中内置了用于读取JSON文件的函数。以下给出几个如何将JSON文件解析为Python对象的示例。
1 将JSON文件读取为字典类型
首先,我们需要导入 json库;
接着,我们使用open函数来读取JSON文件;
最后,利用json.load()函数将JSON字符串转化为Python字典形式.
>>> import json
>>> with open('test.json' ) as f:
... df_test = json.load(f)
>>> type(df_test)
<class 'list'>
>>> type(df_test[0])
<class 'dict'>
>>> df_test[0].keys()
dict_keys(['ID', 'profile', 'tweet', 'neighbor', 'domain', 'label'])
2 将JSON文件读取为Pandas类型
可以使用Pandas库中的 read_json函数来读取对应的JSON文件,
import pandas as pd
df = pd.read_json('test.json')
需要注意的是使用Pandas库不仅仅可以读取电脑本地磁盘上的JSON文件,也可以通过URL读取网络上存放的文件.
>>> import pandas as pd
>>> df1 = pd.read_json('https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json')
>>> df1
squadName homeTown formed secretBase active members
0 Super Hero Squad Metro City 2016 Super tower True {'name': 'Molecule Man', 'age': 29, 'secretIde...
1 Super Hero Squad Metro City 2016 Super tower True {'name': 'Madame Uppercut', 'age': 39, 'secret...
2 Super Hero Squad Metro City 2016 Super tower True {'name': 'Eternal Flame', 'age': 1000000, 'sec...
2.1 使用Pandas读取嵌套JSON类型
我们有时候遇到的JSON文件是嵌套的,这经常会让读取工作变得有些困难. 其实嵌套JSON和Python中的嵌套字典思想类似,即字典中嵌套字典.
(1) 使用apply方法
>>> df_test = pd.read_json('test.json')
>>> df_test['profile'].apply(pd.Series)
id id_str name ... default_profile default_profile_image favourites_count
0 1188812492010487808 1188812492010487808 Sharon Israel ⭐️⭐️⭐️ ... True False NaN
1 155659213 155659213 Cristiano Ronaldo ... False False 2
2 147725246 147725246 FoxNewsInsider ... False False 762
3 1296248637194895360 1296248637194895360 El Realista ... True False 0
3 导出JSON
(1) 使用json.dump()函数将字典写入文件;
json.dump(df_test, 'path')
(2) 我们也可以使用Pandas中的to_json()函数;
dftest.to_json('path')
4 格式化输出
在终端直接打印json文件,通常会得到很不美观的输出;
(1) 可以在函数json.dump中采用参数indent参数来控制输出格式
>>> with open('test.json') as f:
... df = json.load(f)
>>> with open('df_test.json','w') as f:
... json.dump(df[0:4],f,indent = 4)
(2) 使用pandas的to_json
test_polotics.to_json(path1, orient = 'records', indent=4)
5 list类型转化为json文件对应的DataFrame类型
当对json文件进行划分时,使用list保存时,将内容保存到json文件时,需要将list转化为DataFrame类型;
转化方式:
from pandas.core.frame import DataFrame
train_human = ...
train_huamn = DaraFrame(train_human)
train_human.to_json('path')