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

如何将含多行值的Debian control文件转换为JSON?

问题描述

尝试用Python将Debian control文件转换为JSON格式,该文件中存在像Build-Depends这类值跨多行的键值对。现有代码处理时,因为换行的行不含冒号,抛出ValueError,需要修改代码让Build-Depends的多行内容作为对应键的完整值。

现有代码

import json
filename = 'thunar-volman/debian/control'
dict1 = {}
with open(filename) as fh:
    for line in fh:
        print(line)
        command, description = line.strip().split(': ')
        print(command)
        print(description)
        dict1[command.strip()] = description.strip()

with open("test.json", "w") as out_file:
    json.dump(dict1, out_file, indent=4, sort_keys = False)

错误信息

Build-Depends
debhelper-compat (= 13),
               intltool,

Traceback (most recent call last):
  File "read.py", line 7, in <module>
    command, description = line.strip().split(': ')
ValueError: not enough values to unpack (expected 2, got 1)

解决方案

核心思路是跟踪当前正在处理的键,当遇到以缩进开头的行时,将内容追加到前一个键的值中。修改后的代码如下:

import json

filename = 'thunar-volman/debian/control'
control_dict = {}
current_key = None

with open(filename, 'r', encoding='utf-8') as fh:
    for line in fh:
        stripped_line = line.strip()
        # 跳过空行
        if not stripped_line:
            continue
        # 判断是否是新的键值对行(包含冒号)
        if ': ' in stripped_line:
            # 只分割一次,避免值中存在冒号导致错误
            key, value = stripped_line.split(': ', 1)
            current_key = key.strip()
            control_dict[current_key] = value.strip()
        else:
            # 处理续行,追加到当前键的值中
            if current_key is not None:
                control_dict[current_key] += ' ' + stripped_line

# 写入JSON文件,保留非ASCII字符
with open("test.json", "w", encoding='utf-8') as out_file:
    json.dump(control_dict, out_file, indent=4, ensure_ascii=False, sort_keys=False)

关键改进点

  • 新增current_key变量,用于记录当前正在处理的键,遇到续行时直接追加内容
  • 使用split(': ', 1)只做一次分割,避免值中包含冒号时触发错误
  • 跳过空行,减少无效处理
  • 写入JSON时添加ensure_ascii=False,防止特殊字符被转义,保证内容可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:52:51