网络编程
位置:首页>> 网络编程>> Python编程>> python中json格式处理和字典的关系

python中json格式处理和字典的关系

作者:流花飞羽8  发布时间:2021-04-10 04:35:12 

标签:python,json,格式,字典

前言:作为测试工程师都知道,json格式的文件使我们常用的一种数据存放形式,那么对于python文件的处理,python语言有着得天独厚的条件,json的本质是键值对形式存储的,这就非常像python语言中的字典,所以有很多字典形式的函数与方法,是直接可以使用的。

今天我们先讲一下编写python脚本处理json的核心功能,有些散乱,后期在进行整体脚本的编写。

1、json文件读取后的操作

json文件读取后的操作和字典的操作一样,可以将dict中相关的内置方法都继承过来,但是json文件中会有list形式和dict形式的混合存在。

此时要注意区分。

json文件数据结构走的是dict的结构,键值对

(1)修改值非常方便,

json["id"]=3001

(2)修改键就麻烦一点。

dict字典没有直接修改键的概念与方法,

修改键:先把原有的键值对删除,在添加新的键值对,注意获取旧键值对的value,传递给新的键值对的value

获取value:value=json['request']["session_id"]

删除键值对:json['request'].pop("session_id")

新增键值对:json['request'].setdefault("operation_id",value)

2、python递归路径文件夹中的所有文件

def jsonfilePath_read(inputfilePath, outfilepath):
   rightCount = 0
   errorCount = 0
   for file in os.listdir(inputfilePath):
       try:
           print(file)
           read_jsonfile_change2(str(inputfilePath + '/' + file), outfilepath + '/' + file)
           print(file + '修改成功')
           rightCount += 1
       except:
           print(file + '文件有误修改失败')
           errorCount += 1

print('文件修改完成 ', rightCount, '个文件成功', errorCount, '个文件有误')

解说核心代码:

核心代码:
for file in os.listdir(inputfilePath):
   #file就是当前路径中的所有文件名,使用的时候别忘了路径+'/' + file
   try:
       ....inputfilePath + '/' + file
   except:
       print().....

3、json文件的读取与写入新文件

读一遍写一遍可以实现json的格式化,解决json在txt文件中是单行显示的问题。

# 读取文件
with open('file/test.json', 'r', encoding='utf8') as f:
   json_data = json.load(f)
jsondict = json_data

# 写入新文件
with open('outfile/test.json', 'w', encoding='utf8') as r:
   json.dump(jsondict, r, ensure_ascii=False, indent=4)
print('新文件生成完成')

核心点说明:

读取、写入encoding='utf8' 防止编码问题 indent=4,好像是空4个格,美观输出

来源:https://blog.csdn.net/u013521274/article/details/125119342

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com