JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。
使用 JSON 函数需要导入 json 库:import json。
JSON函数:
json.dumps 用于将 Python 对象编码成 JSON 字符串。
json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型。
转换格式如图:
转化代码:
import json
class Params():
def __init__(self, json_path):
with open(json_path) as f:
params = json.load(f) # 将json格式数据转换为字典
self.__dict__.update(params)
def save(self, json_path):
with open(json_path, 'w') as f:
json.dump(self.__dict__, f, indent=4) # indent缩进级别进行漂亮打印
def update(self, json_path):
"""Loads parameters from json file"""
with open(json_path) as f:
params = json.load(f)
self.__dict__.update(params)
@property
# Python内置的@property装饰器就是负责把一个方法变成属性调用的
def dict(self):
"""Gives dict-like access to Params instance by `params.dict['learning_rate']"""
return self.__dict__
sta = 'shidaio.jpg'
score = 0.96
x = 988
y = 999
w = 82
h = 838
date = {'info':{'image_name':sta},'ann':[{'score':score,'bbox':[x,y,w,h]},]}
date1 = {'score':score,'bbox':[x,y,w,h]}
date['ann'].append(date1)
date['ann'].append(date1)
test = json.dumps(date)
hhh = 'sjad'
with open(hhh +'.json', 'w') as f: # 创建一个params.json文件
f.write(test) # 将json_str写到文件中
params = Params(hhh +'.json')
params.save(hhh + '.json') # 将修改后的数据保存
批量处理时,引入:
dir = os.listdir(json_path)
for file in dir:
批量处理时,引入:
```python
dir = os.listdir(json_path)
for file in dir: