34 lines
1.3 KiB
Python
34 lines
1.3 KiB
Python
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)}"] |