You need to enable JavaScript to run this app. Python如何解析无分隔符拼接的多个JSON对象并转为合法逗号分隔JSON?
优惠活动
大模型
产品
解决方案
定价
更多

Python如何解析无分隔符拼接的多个JSON对象并转为合法逗号分隔JSON?

拼接无分隔JSON的Python解析实现

原有方案失效原因

  • 提供的原始示例字符串本身存在JSON语法错误:details数组内的元素误写为["id": "a123a"]结构(JSON中带冒号键值对的对象需要以{开头,数组元素不能直接关联键名),同时外层包裹的字符串存在转义混乱问题,本身不是合法的JSON片段,无论使用哪种解析器都会触发语法异常。
  • 编写的raw_decode循环缺少终止逻辑:遍历完所有JSON片段后,指针会走到字符串末尾,下一次调用解析方法会直接触发越界或语法错误,没有设置正常退出的判断条件。

可直接复用的实现代码

import json
from json import JSONDecoder, JSONDecodeError

def parse_concatenated_json(raw_str: str):
    # 前置清洗:根据实际脏数据的语法错误调整替换规则
    cleaned_str = raw_str.replace('details":[\'', 'details":[{"')
    cleaned_str = cleaned_str.replace('"}', '"}')
    decoder = JSONDecoder()
    pos = 0
    parsed_objects = []
    total_len = len(cleaned_str)

    while pos < total_len:
        # 跳过JSON片段之间的空白字符(换行、空格、制表符)
        while pos < total_len and cleaned_str[pos].isspace():
            pos += 1
        if pos >= total_len:
            break
        try:
            # 从当前指针位置解析完整JSON结构
            obj, pos = decoder.raw_decode(cleaned_str, pos)
            parsed_objects.append(obj)
        except JSONDecodeError:
            # 可选容错:跳过无法识别的非法字符,避免全量解析中断
            pos += 1
    return parsed_objects

if __name__ == "__main__":
    # 替换为实际的拼接字符串
    test_input = """
    {"Months": "12", "details":[{"id": "a123a", "text": "something, somethingelse, againwiththesomething", "value": "-2536"}, {"comment": "something", "value": "6500", "id": "abc123"}], "Date": "2017-12-31"}
    {"Months": "9", "details":[{"id": "foo", "text": "something, somethingelse, againwiththesomething", "value": "-656"}, {"comment": "something", "value": "9800", "id": "bar"}], "Date": "2017-12-31"}
    {"Months": "12", "details":[{"id": "woo", "text": "something, somethingelse, againwiththesomething", "value": "3776"}, {"comment": "something", "value": "600", "id": "tar"}], "Date": "2017-12-31"}
    """
    result = parse_concatenated_json(test_input)
    # 输出为标准合法的、逗号分隔的JSON格式
    valid_json = json.dumps(result, ensure_ascii=False, indent=2)
    print(valid_json)

实现核心逻辑

  • 指针自动跳过JSON片段间的空白字符,避免换行、空格卡在两个JSON结构之间导致解析位置错位。
  • 增加字符串边界判断,当指针遍历到末尾时自动终止循环,不会出现无限循环或索引越界问题。
  • 内置容错分支,遇到零散非法字符时自动跳过该位置继续解析,适配实际业务中常见的脏数据场景。
  • 最终通过json.dumps将解析得到的对象列表序列化为标准JSON数组,自动完成逗号分隔、语法校验,不需要手动拼接字符串保证格式合法性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.31 23:45:07