import json import os def generate_json_from_list(data, output_path): """ 将 list 类型的数据写入指定路径的 JSON 文件中。 :param data: 要写入的列表数据 :param output_path: 输出 JSON 文件的完整路径 """ try: # 确保输出目录存在 os.makedirs(os.path.dirname(output_path), exist_ok=True) # 写入 JSON 文件 with open(output_path, 'w', encoding='utf-8') as f: json.dump(data, f, indent=4, ensure_ascii=False) print(f"JSON 文件已成功写入:{output_path}") except Exception as e: print(f"写入 JSON 文件时发生错误:{e}") # 示例调用 if __name__ == "__main__": data = [ { 'binOveron': 'no', 'binReprobe': 'no', 'binType': 'bad', 'hardBin': '2', 'hardBinName': 'OS_failed', 'lslFt': '-150', 'lslQA': '-150', 'lslTypFt': 'GE', 'lslTypQA': 'GE', 'softBin': '2000', 'softBinName': 'OS_PS_failed', 'testInstName': '**.OS_PS.ptdGroup[VDD]', 'testName': 'ptd', 'testNumber': '20000100', 'testRemarks': '', 'unitFt': 'uA', 'unitQA': 'uA', 'uslFt': '10000', 'uslQA': '10000', 'uslTypFt': 'LE', 'uslTypQA': 'LE' }, { 'binOveron': 'no', 'binReprobe': 'no', 'binType': 'bad', 'hardBin': '2', 'hardBinName': 'OS_failed', 'lslFt': '-150', 'lslQA': '-150', 'lslTypFt': 'GE', 'lslTypQA': 'GE', 'softBin': '2000', 'softBinName': 'OS_PS_failed', 'testInstName': '**.OS_PS.ptdGroup[VDD_AVS]', 'testName': 'ptd', 'testNumber': '20000200', 'testRemarks': '', 'unitFt': 'uA', 'unitQA': 'uA', 'uslFt': '10000', 'uslQA': '10000', 'uslTypFt': 'LE', 'uslTypQA': 'LE' } ] output_file = "C:/Users/lwx1431831/Desktop/ods/sabc.json" generate_json_from_list(data, output_file) 我希望循环data的时候,对没一个属性进行判断然后生成json文件
时间: 2025-06-30 13:19:00 浏览: 4
你的需求是:**在将 `data` 列表写入 JSON 文件之前,对列表中每个字典元素的属性进行判断或处理,然后再生成最终的 JSON 文件**。
---
## ✅ 回答问题
你希望在写入 JSON 文件前对 `data` 中的每一个字段(键值对)进行检查、过滤或转换。这可以通过一个额外的函数来实现,该函数对每个字典项进行遍历和处理。
---
## ✅ 解决方案代码如下:
```python
import json
import os
def process_item(item):
"""
对 data 中的每一个字典项进行处理。
你可以在这里添加字段过滤、类型转换、重命名等操作。
:param item: 字典对象
:return: 处理后的字典
"""
processed = {}
for key, value in item.items():
# 示例1:过滤掉空字符串的字段
if value == '':
continue
# 示例2:将某些字段转为整数(如 testNumber)
if key in ['testNumber', 'softBin', 'hardBin']:
try:
processed[key] = int(value)
except (ValueError, TypeError):
processed[key] = value # 转换失败保留原值
# 示例3:统一单位字段的格式
elif key in ['unitFt', 'unitQA']:
processed[key] = value.lower() if isinstance(value, str) else value
# 示例4:其他字段直接保留
else:
processed[key] = value
return processed
def generate_json_from_list(data, output_path):
"""
将 list 类型的数据经过处理后写入指定路径的 JSON 文件中。
:param data: 要写入的列表数据(包含多个字典)
:param output_path: 输出 JSON 文件的完整路径
"""
try:
# 确保输出目录存在
os.makedirs(os.path.dirname(output_path), exist_ok=True)
# 对 data 中的每一项进行处理
processed_data = [process_item(item) for item in data]
# 写入 JSON 文件
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(processed_data, f, indent=4, ensure_ascii=False)
print(f"JSON 文件已成功写入:{output_path}")
except Exception as e:
print(f"写入 JSON 文件时发生错误:{e}")
# 示例调用
if __name__ == "__main__":
data = [
{
'binOveron': 'no', 'binReprobe': 'no', 'binType': 'bad', 'hardBin': '2',
'hardBinName': 'OS_failed', 'lslFt': '-150', 'lslQA': '-150',
'lslTypFt': 'GE', 'lslTypQA': 'GE', 'softBin': '2000',
'softBinName': 'OS_PS_failed', 'testInstName': '**.OS_PS.ptdGroup[VDD]',
'testName': 'ptd', 'testNumber': '20000100', 'testRemarks': '',
'unitFt': 'uA', 'unitQA': 'uA', 'uslFt': '10000', 'uslQA': '10000',
'uslTypFt': 'LE', 'uslTypQA': 'LE'
},
{
'binOveron': 'no', 'binReprobe': 'no', 'binType': 'bad', 'hardBin': '2',
'hardBinName': 'OS_failed', 'lslFt': '-150', 'lslQA': '-150',
'lslTypFt': 'GE', 'lslTypQA': 'GE', 'softBin': '2000',
'softBinName': 'OS_PS_failed', 'testInstName': '**.OS_PS.ptdGroup[VDD_AVS]',
'testName': 'ptd', 'testNumber': '20000200', 'testRemarks': '',
'unitFt': 'uA', 'unitQA': 'uA', 'uslFt': '10000', 'uslQA': '10000',
'uslTypFt': 'LE', 'uslTypQA': 'LE'
}
]
output_file = "C:/Users/lwx1431831/Desktop/ods/sabc.json"
generate_json_from_list(data, output_file)
```
---
## ✅ 说明与解释
| 功能 | 描述 |
|------|------|
| `process_item()` 函数 | 用于处理每一个字典项,可以做字段过滤、类型转换、重命名等操作 |
| `os.makedirs(...)` | 自动创建输出路径中的父目录,防止文件写入失败 |
| `json.dump(..., indent=4)` | 美化输出格式,便于查看 |
| `ensure_ascii=False` | 支持中文等非 ASCII 字符 |
| `processed_data = [process_item(item)]` | 遍历整个 `data` 列表并对每个元素进行处理 |
---
阅读全文
相关推荐


















