python读取json文件转化为list_python操作json文件:读取、写入、追加、删除、excel转json、json转excel...

import json

class GetJsonData:

def json_data(self, *json_file):

'''

:description:获取json文件数据

:param json_file: 输入json文件名,默认为ranzidata.json

:return: 返回数据类型为dict

'''

if len(json_file) == 1:

part_path = 'ranzi/ranzi_config/' + str(json_file[0])

file_path = GetPath().get_path(part_path)

else:

file_path = GetPath().get_path('ranzi/ranzi_config/ranzidata.json')

#读取json文件

with open(file_path, mode='r', encoding='utf-8') as jf:

jd = json.load(jf)

return jd

def excel_to_json(self, excel_file_path, sheet_name, key_name):

'''

:description:将excel数据转化成json文件数据格式输出

:param excel_file_path: excel文件路径

:param sheet_name: 工作表名

:param key_name: 定义键值

:return:

'''

wb = openpyxl.load_workbook(excel_file_path)

get_sheet = wb[sheet_name]

list_tmp = []

list_data = []

stat = True

json_data = {}

for get_row in get_sheet:

if stat:

stat = False

continue

for get_cell in get_row:

list_tmp.append(str(get_cell.value))

list_data.append(list_tmp)

list_tmp = []

json_data[key_name] = list_data

return json_data

def json_to_excel(self, json_file, excel_path):

wb = Workbook()

data = self.json_data(json_file)

k = data.keys()

for sheet_name in k:

try:

wb.remove(sheet_name) # 如表已存在则移除工作表

except:

pass

wb.create_sheet(sheet_name, 0)#创建表

ws = wb[sheet_name]#操作指定表

sheet_data = data[sheet_name]#获取表要写入的数据

for t in range(1, len(sheet_data) + 1): # 遍历要写入的行数

i = 65 # ASCII码'65'表示'A'

for j in range(1, len(sheet_data[t - 1]) + 1): # 遍历每行要写入的数量

ws['%s%d' % (chr(i), t)] = sheet_data[t - 1][j - 1]

i += 1

wb.save(excel_path)

def json_update(self, dict_new, *json_file):

if len(json_file) == 1:

part_path = 'ranzi/ranzi_config/' + str(json_file[0])

file_path = GetPath().get_path(part_path)

else:

file_path = GetPath().get_path('ranzi/ranzi_config/ranzidata.json')

json_data = self.json_data()

json_data.update(dict_new)

with open(file_path, mode='w', encoding='utf-8') as jf:

json.dump(json_data, jf, indent=2, sort_keys=True, ensure_ascii=False)

def json_del(self, key, *json_file):

if len(json_file) == 1:

part_path = 'ranzi/ranzi_config/' + str(json_file)

file_path = GetPath().get_path(part_path)

else:

file_path = GetPath().get_path('ranzi/ranzi_config/ranzidata.json')

json_dict = self.json_data(file_path)

json_data = json_dict.pop(key)

print(json_data, 'delete success')

with open(file_path, mode='w', encoding='utf-8') as jf:

json.dump(json_dict, jf, indent=2, sort_keys=True, ensure_ascii=False)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值