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

Python中如何将文件内非标准对象转换为标准JSON格式

问题描述

我存储对象的文件中包含如下非标准格式的内容:

{ 
    name: (sindey, crosby)
    game: "Hockey"
    type: athlete
},
{ 
    name: (wayne, gretzky)
    game: "Ice Hockey"
    type: athlete
}

需要将上述内容转换为标准JSON格式,期望输出如下:

[
    { 
        "name": "(sindey, crosby)",
        "game": "Hockey",
        "type": "athlete"
    },
    { 
        "name": "(wayne, gretzky)",
        "game": "Ice Hockey",
        "type": "athlete"
    }
]

此前我已经实现了|分隔逐行格式的转换逻辑,这类输入的示例格式为:

name: (sidney, crosby) | game:"Hockey" |  type:athlete 
 name: (wayne, gretzky) | game:"Ice Hockey" |  type:athlete

对应已有的可运行代码如下:

import json

f = open("log.file", "r")
content = f.read()
splitcontent = content.splitlines()

d = []
for v in splitcontent:
    l = v.split(' | ')
    d.append(dict(s.split(':',1) for s in l))


with open("json_log.json", 'w') as file:
    file.write((json.dumps(d, indent=4, sort_keys= False)))

现在需要调整上述代码,实现大括号包裹格式输入到标准JSON的转换。


改造方案

不需要引入额外依赖,只需要新增大括号对象块的拆分预处理逻辑,即可复用原有键值解析、JSON输出的逻辑,调整后的完整代码如下:

import json
import re

# 读取原始输入文件
with open("log.file", "r", encoding="utf-8") as f:
    content = f.read()

result = []
# 拆分独立对象块:清理首尾多余的大括号、逗号,按对象边界切分
raw_blocks = re.split(r'},?\s*\{', content.strip().strip("{},"))
for block in raw_blocks:
    current_obj = {}
    # 逐行解析单个对象内的键值对
    for line in block.splitlines():
        line = line.strip().strip(",")
        if not line:
            continue
        key, value = line.split(":", 1)
        # 清理键值前后的空格、冗余引号
        current_obj[key.strip().strip('"')] = value.strip().strip('"')
    result.append(current_obj)

# 输出标准JSON文件
with open("json_log.json", "w", encoding="utf-8") as f:
    json.dump(result, f, indent=4, ensure_ascii=False, sort_keys=False)

核心改造点

  • 替换原来的|分隔逻辑,用正则匹配大括号对象的分隔边界,把整段连续的多对象内容拆成独立单对象块
  • 逐块遍历的时候沿用原有按冒号拆分键值对的逻辑,统一清理键值两侧多余的空格、包裹的冗余引号
  • 完全保留原有JSON输出的格式配置,输出结果和之前|分隔格式的输出规范一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 21:57:23