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

Anytree库JSON导出器西里尔字母显示异常问题求助

解决Anytree导出JSON时西里尔字符转义的问题

问题分析

你遇到的核心问题是重复序列化导致的二次转义:JsonExporter.export(root)已经帮你生成了完整的JSON字符串(内部已经处理了字符编码逻辑),但你又用json.dump(data, outfile, ensure_ascii=False)把这个JSON字符串当成普通文本再次做了序列化操作,这就把原本正常的西里尔字符转成了\uXXXX格式的转义序列。

而你直接写入JSON字符串的测试案例能正常显示,就是因为跳过了二次序列化的步骤,直接把原生JSON内容写入了文件。

修正方案

有两种简洁的解决方式,任选其一即可:

方式1:直接写入导出的JSON字符串

既然JsonExporter.export()已经生成了正确的JSON内容,我们不需要再用json.dump多此一举,直接用文件的write方法写入即可:

import json, pprint
from anytree import AnyNode, RenderTree
from anytree.exporter import JsonExporter
from anytree.importer import JsonImporter

json_file = r'd:\temp\test.json'

# 构建树形结构
root = AnyNode(uk='узел-0', parent=None)
b = AnyNode(uk='узел-01', parent=root)
a = AnyNode(uk='узел-011', parent=b)
g = AnyNode(uk='узел-021', parent=root)

print('\nTree for export:')
print(RenderTree(root).by_attr('uk'))

# 导出:直接写入导出的JSON字符串
exporter = JsonExporter(indent=2, sort_keys=True, ensure_ascii=False)  # 关键:添加ensure_ascii=False
data = exporter.export(root)
with open(json_file, 'w', encoding='utf-8') as outfile:
    outfile.write(data)  # 直接写入,避免二次序列化

# 导入验证
importer = JsonImporter()
with open(json_file, encoding='utf-8') as json_file:
    data = json.load(json_file)
root = importer.import_(data)

print('\nImported tree:')
print(RenderTree(root).by_attr('uk'))

print('\nData in JSON-file:')
pprint.pprint(data)

方式2:使用JsonExporter的write方法(更简洁)

Anytree的JsonExporter本身提供了write方法,可以直接将树形结构写入文件,完全不用手动处理字符串:

# 把原来的导出代码替换成这段
exporter = JsonExporter(indent=2, sort_keys=True, ensure_ascii=False)
with open(json_file, 'w', encoding='utf-8') as outfile:
    exporter.write(root, outfile)

关键改动说明

  • 初始化JsonExporter时一定要加ensure_ascii=False参数,这会让导出的JSON直接保留西里尔字符,不做转义。
  • 绝对不要对JsonExporter.export()生成的JSON字符串再次调用json.dump,否则会触发二次转义,把正常字符变成\uXXXX格式。

修正后的效果

此时你的JSON文件里会直接显示正常的西里尔字符:

{
  "children": [
    {
      "children": [
        {
          "uk": "узел-011"
        }
      ],
      "uk": "узел-01"
    },
    {
      "uk": "узел-021"
    }
  ],
  "uk": "узел-0"
}

同时导入后的树形结构依然和导出前完全一致,不会有任何显示问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 21:37:54