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

Python是否存在可加载并清理无引号键值类JSON文件的模块?

Python处理无引号键值类JSON文件的方案

有几个现成的Python模块可以处理这种类JSON(无引号键/字符串值)的文件,下面是具体实现方案:

1. 使用demjson模块

demjson专门支持解析非标准JSON格式,包括无引号的键和未加引号的字符串值。

  • 安装:pip install demjson
  • 示例代码:
import demjson
import json

# 读取目标文件
with open('sample.txt', 'r') as f:
    raw_content = f.read()

# 解析非标准JSON内容
parsed_data = demjson.decode(raw_content)

# 转换为标准JSON并写入新文件
with open('cleaned_sample.json', 'w') as f:
    json.dump(parsed_data, f, indent=2)

2. 使用json5模块

JSON5规范本身允许无引号键和未加引号的字符串值,该模块可直接解析这类内容。

  • 安装:pip install json5
  • 示例代码:
import json5
import json

with open('sample.txt', 'r') as f:
    raw_content = f.read()

# 解析类JSON内容
parsed_data = json5.loads(raw_content)

# 输出标准JSON文件
with open('cleaned_sample.json', 'w') as f:
    json.dump(parsed_data, f, indent=2)

3. 使用Python内置ast模块

如果不想安装第三方库,ast.literal_eval可以安全解析符合Python字典语法的类JSON内容(你的示例刚好满足要求)。

  • 示例代码:
import ast
import json

with open('sample.txt', 'r') as f:
    raw_content = f.read()

# 解析为Python字典
parsed_data = ast.literal_eval(raw_content)

# 转换为标准JSON
with open('cleaned_sample.json', 'w') as f:
    json.dump(parsed_data, f, indent=2)

以上三种方法都能将你提供的sample.txt转换为合法JSON,最终输出的cleaned_sample.json内容如下:

{
  "apple": ["green", "red"],
  "kiwi": ["green", "gold"],
  "strawberry": "red"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:25:24