且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

json 文件的读取与储存| 学习笔记

更新时间:2022-09-07 23:31:16

开发者学堂课程【Python 数据分析库 Pandas 快速入门json 文件的读取与储存学习笔记,与课程紧密联系,让用户快速学习知识。

课程地址https://developer.aliyun.com/learning/course/607/detail/8858


json 文件的读取与储存


Json 是我们常用的一种数据交换格式,前面在前后端的交互经常用到,也会在存储的时候选择这种格式。

所以我们需要知道 Pandas 如何进行读取和存储 JSON 格式。


读取文件

pd.read_json(path)

需要用到的参数:

orient = “records”:

告诉 API 以怎样的格式展示读取的 json 文件

'split' : dict like {index -> [index], columns -> [columns], data -> [values])

'records' : list like [fcolumn -> value}, ... , {column -> value}]

'index' : dict like {index -> {column -> value})

'columns' : dict like {column -> {index -> value},默认该格式

'values' : just the values array

lines = True/False:

是否按行读取 json 对象

实例:

In:

pd.read_hdf ( "test.h5" , key="close" ).head( )

In:

sa = pd.read_json  ( "Sarcasm_Headlines_Dataset.json", orient = "records ", line = True)   //以一行作为一个样本


存储文件

df.to_json(path)

需要用到的参数(与读取相同):

orient = “records”

lines = True/False:

实例:

In:

sa.to_json ( "test-json" , orient="records" )

未指定 lines 后保存的当前文件夹下的 json 文件未以一行为样本,仅用逗号分隔。

In:

sa.to_json ( "test-json" , orient="records" , lines = True)

此时保存的文件格式就是以一行为样本。