python存储json文件(python json文件处理)

http://www.itjxue.com  2023-04-01 06:11  来源:未知  点击次数: 

python写入json文件

想要多条相同key的数据添加json中,先将数据存入到字典中,再 append 到列表中。最后存入json中。

这样子list才会是下图所示的样子。

python3 读excel转Json文件

from xlrd import *

import json

# 参考1-字典、列表转JSON:

# 参考2-JSON直接保存到文件:

# 从excel读取数据存放到列表中

def readExcel():

? ??keyData=[]? ?# 定义空List,用于保存读到的行数据

????excelBook=open_workbook("data.xlsx")? ? # 从当前目录读取《data.xlsx》文件

????table=excelBook.sheet_by_name("data")? # 从《data.xlsx》中找名为 data的sheet页

????rowNum=table.nrows? # 获取《data.xlsx》--data页中?行数

????colNum=table.ncols? # 获取《data.xlsx》--data页中 列数

? ??colName=table.row_values(0)? ? # 取第一行数据,即列名,colName 是个List

????# print(colName)

????if rowNum=1:

????????print("没数据...")? ? # 如果行数=1,说明没有数据,因第1行一般定义为列名

????else:

????????for i in range(rowNum-1):

????????????d={}? ? # 定义空字典,用于存放获取到数据

????????????values=table.row_values(i+1)? ? # 获取每行的数据,values最终是个List

????????????# print(values)

????????????for x in range(colNum):? ? #? 每个列作为字典的一组数据

????????????????d[colName[x]]=values[x]? ?#? 用colName值作为字典的key,values值作业为字典的value

????????????????# print(d)

????????????keyData.append(d)? ? # 读完一行数据保存到字典,再保存到列表

????# print(keyData)

????return keyData? ?#? 全部数据读完并保存到列表后,返回

#? 列表转Json

def listToJson():

? ? ?keyParam=readExcel()? ? # 调用从excel读取数据的函数,把数据保存到列表

????CaseConfig=open("CaseConfig.json", mode="w+")? ? #? 创建json文件

????CaseConfig.write('{\n"key":')? ? # 往json文件中写数据,先写json的格式的{,和模块名

???? ?# 把从excel读取的数据转成Json格式保存入 CaseConfig,indent=4是进行格式化,使json排版好看

????json.dump(keyParam, CaseConfig, indent=4)??

????CaseConfig.write('\n}')? ?# 往json文件中写数据,写结尾的 },写前先换行

????CaseConfig.close()? ? # 关闭json文件,必要!!

if __name__ == '__main__':? ? ? ? #? 调试调用

????listToJson()

python中json处理

python中json文件处理涉及的四个函数json.loads()、json.dumps()、json.load()、json.dump()。

1)json.dumps()

????将一个Python数据类型dict进行json格式的编码(字典-字符串)

? ? eg:

????age_dict = {'age1':'12', 'age2':'15'}

????json_info = json.dumps(age_dict)

????print("json_info = {}".format(json_info))

????print("json_info type = {}".format(type(json_info)))

2)json.loads()

????将json格式数据转换为dict(字符串-字典)

????json_age ='{"age1": "12", "age2": "15"}'

????dict_age = json.loads(json_info)

????print("json_age = {}".format(json_age))

????print("dict_age type = {}".format(str(type(dict_age))))

3)json.load()

????读取文件,将里json格式字符串转化为dict

????with open(test.json, 'r') as file:

? ? ????contents = json.load(file)

????print(contents)

4)json.dump()

????将dict类型转换为json格式字符串,存入文件

????number = [1, 2, 3, 5]

????file = 'number.json'

????with open(file?, 'w') as file:

? ? ????json.dump(number, file)

python 下载数据json 2021-02-27

import json

#探索数据的结构

filename = 'data/1.json'

with open(filename) as f:

? ? all_eq_data = json.load(f)? ? #存储进去一个json数据对象

'''

readable_file = 'data/readable_eq_data.json'? ? #创建一个文件对象

with open(readable_file,'w') as f:

? ? json.dump(all_eq_data,f,indent = 4)? ? #接受一个json数据对象和文件对象? ? indent缩进

'''

all_eq_dicts = all_eq_data['features']? ? #提取键"features"数据并储存

mags,titles,lons,lats= [],[],[],[]

for eq_dict in all_eq_dicts:

? ? mag = eq_dict['properties']['mag']? ? #每次地震震级存储在'properties'部分的'mag'下

? ? title = eq_dict['properties']['title']? ? #存储title

? ? lon?= eq_dict['geometry']['coordinates'][0]????

? ??lat = eq_dict['geometry']['coordinates'][1]

? ? mags.append(mag)

? ? titles.append(title)

? ? lons.append(lon)

? ? lats.append(lat)

print(mags[:10])????#提取震级

#print(len(all_eq_dicts))? ? #提取所有地震的次数

print(titles[:2])

print(lons[:5])

print(lats[:5])

绘制震级散点图:

import plotly.express as px

fig = px.scatter(

? ? x = lons,

? ? y = lats,

? ? labels = {'x':'经度','y':'纬度'},

? ? range_x = [-200,200]

? ? range_y = [-90,90]

? ? width = 800,

? ? height = 800,

????title = '全球地震散点图'

)

fig.write_html('global_earthquakes.html')? ? #保存文件

fig.show()? ? #显示

另一种指定图标数据的方式:

import pandas as pd

data = pd.DataFrame(

? ? data = zip(lons,lats,titles,mags),columns = ['经度','纬度','位置','震级']? ? #封装数据

)

data.head()

然后参数配置方式可以从:

? ? x = lons,

? ? y = lats,

? ? labels = {'x':'经度','y':'纬度'},

变更为:

????data,

? ? x = '经度'

? ? y = '纬度'

? ? ……

? ? size = '震级',

? ? size_max = 10,? ? #默认20

? ? color = '震级',? ? #标记颜色 蓝红黄

? ? hover_name = '位置',? ? #添加鼠标指向时显示的文本

? ??

(责任编辑:IT教学网)

更多

推荐新书快递文章