jb_fr/scripts/json数组元素字段拼接.py
2025-06-06 21:04:04 +08:00

34 lines
1.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import json
import re
def process(input_strings: list) -> list:
"""解析 JSON 数组,提取用户指定的字段并按模板拼接"""
json_str, template = input_strings[0], input_strings[1]
try:
# 解析 JSON
data = json.loads(json_str)
if not isinstance(data, dict) or "data" not in data or not isinstance(data["data"], list):
return ["错误JSON 格式无效,缺少 'data' 数组或不是数组"]
# 提取模板中的字段名(形如 $field$
fields = re.findall(r'\$([^\$]+)\$', template)
if not fields:
return ["错误:模板中未找到有效字段(格式如 $field$"]
# 拼接结果
result = []
for item in data["data"]:
# 替换模板中的字段
formatted = template
for field in fields:
# 获取字段值,缺失时用 "N/A"
value = str(item.get(field, "N/A"))
formatted = formatted.replace(f"${field}$", value)
result.append(formatted)
# 返回拼接字符串
return [",".join(result)] if result else ["无有效数据"]
except json.JSONDecodeError:
return ["错误:无效的 JSON 字符串"]
except Exception as e:
return [f"错误:{str(e)}"]