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

Python中Properties转JSON时如何避免ASCII字符多反斜杠

解决Properties转JSON时ASCII字符前多余反斜杠的问题

你遇到的问题根源在于:Python读取Properties文件时,把文件里的Unicode转义序列(比如\u9078)当成了普通字符串(也就是Python里的'\\u9078',包含反斜杠和u等字符),而json.dump默认会对字符串中的反斜杠进行转义,导致最终输出变成了\\u9078,多出了一层反斜杠。

解决方案:解码Unicode转义序列后再序列化

只需要在读取Properties的value时,先将转义序列解码为实际的Unicode字符,再交给json.dump处理——因为json.dump默认会把非ASCII字符自动转换为标准的Unicode转义序列(\uXXXX格式),正好符合你的预期。

修改后的代码如下:

import json
def convertPropertiesToJson(fileName, outputFileName, sep='=', comment_char='#'):
    props = {}
    with open(fileName, "r") as f:
        for line in f:
            l = line.strip()
            if l and not l.startswith(comment_char):
                innerProps = {}
                keyValueList = l.split(sep)
                key = keyValueList[0].strip()
                keyList = key.split('.')
                # 添加转义序列解码逻辑
                value = sep.join(keyValueList[1:]).strip().encode('utf-8').decode('unicode-escape')
                if keyList[1] not in props:
                    props[keyList[1]] = {}
                innerProps[keyList[2]] = value
                props[keyList[1]].update(innerProps)
    with open(outputFileName, 'w') as outfile:
        json.dump(props, outfile)

convertPropertiesToJson("sample.properties", "sample.json")

验证结果

运行修改后的代码,输出的sample.json内容会变成:

{"key": {"CHOOSE": "\u9078\u629e"}}

完全符合你的预期。

补充说明

  • 如果你希望JSON直接输出实际的汉字(而不是Unicode转义序列),可以在json.dump时添加ensure_ascii=False参数,这样输出会是{"key": {"CHOOSE": "选择"}}。
  • 这种解码方式也能处理Properties文件中其他合法的Unicode转义序列,比如\u4e2d\u6587等,适用性更广。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:11:26