You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现带键值对的列表转指定JSON格式问题求助

问题:转换配置字符串列表为指定JSON格式

我在Python开发中,通过以下代码获取包含键值对的字符串列表:

show_config = self.show_task(ha_task)
show_config = show_ha_config["tasks"][0]["task-details"][0]["output"]
# need to decode into base64
show_decoded = base64.b64decode(
    bytes(show_config, "utf-8")
).decode("ascii")
show_conf = show_decoded.split("\n")
return show_conf

返回的show_conf为:

[
    '',
    'VSID:            0   ',
    'VRID:            0   ',
    'Type:            VSX Gateway',
    'Name:            chckpt-fw1a',
    'Security Policy: VS-policy',
    'Installed at:    12Jan2023 21:57:15',
    'SIC Status:      Trust',
    'Connections number: 52',
    'Connections peak: 152',
    'Connections limit:  14900',
]

使用json_format = json.dumps(show_conf)转换得到的JSON不符合需求,当前JSON为:

["", "VSID:            0   ", "VRID:            0   ", "Type:            VSX Gateway", "Name:            chckpt-fw1a", "Security Policy: VS-policy", "Installed at:    12Jan2023 21:57:15", "SIC Status:      Trust", "Connections number: 52", "Connections peak:   152", "Connections limit:  14900"]

需要的目标JSON格式为:

["", 
"\"VSID\": \"0\"   ",
"\"VRID\": \"0\"   ",
"\"Type\":   \"VSX Gateway\"",
"\"Name\": \"chckpt-fw1a\"",
"\"Security Policy\": \"VS-policy\"",
"\"Installed at\":    \"12Jan2023 21:57:15\"",
"\"SIC Status\":      \"Trust\"",
"\"Connections number\": \"52\"",
"\"Connections peak\":   \"152\"",
"\"Connections limit\":  \"14900\""
]

解决方案

核心思路是遍历show_conf中的每个字符串,将符合key: value格式的条目转换为带双引号的"key": "value"格式(保留原字符串末尾的空格),空字符串则直接保留。

修改后的代码如下:

import base64
import json

# 原有的解码和分割逻辑保持不变
show_config = self.show_task(ha_task)
show_config = show_ha_config["tasks"][0]["task-details"][0]["output"]
show_decoded = base64.b64decode(bytes(show_config, "utf-8")).decode("ascii")
show_conf = show_decoded.split("\n")

# 处理每个字符串,转换为目标格式
processed_conf = []
for line in show_conf:
    if not line.strip():  # 处理空字符串或仅含空格的行
        processed_conf.append(line)
        continue
    # 分割键和值:按第一个冒号分割,避免键名含冒号的情况
    key_part, value_part = line.split(":", 1)
    # 提取原行末尾的空格,保留原格式排版
    trailing_spaces = line[len(key_part) + len(value_part) + 1:] if len(line) > len(key_part) + len(value_part) + 1 else ""
    # 拼接成带引号的格式
    formatted_line = f'"{key_part.strip()}": "{value_part.strip()}"{trailing_spaces}'
    processed_conf.append(formatted_line)

# 转换为带换行缩进的JSON
json_format = json.dumps(processed_conf, indent=2)
return processed_conf  # 按需返回处理后的列表或JSON字符串

代码说明:

  1. 空行处理:直接保留原空字符串,不做修改。
  2. 键值分割:用split(":", 1)仅按第一个冒号分割,避免键名包含冒号时出错。
  3. 保留末尾空格:通过计算原行与分割后内容的长度差,提取原行末尾的空格,保证和原格式排版一致。
  4. JSON格式化:json.dumps的indent=2参数实现换行缩进,匹配目标格式的排版要求。

运行上述代码后,生成的JSON将完全符合需求。


内容的提问来源于stack exchange,提问作者Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 02:45:18