python - 如何使用 python 处理读取其中有注释的 .json 文件?

标签 python json

首先,我知道注释不是有效的 json。也就是说,出于某种原因,我必须处理的这个 .json 文件在行首和行尾有注释。

我如何在 python 中处理这个问题并基本上加载 .json 文件但忽略注释以便我可以处理它?我目前正在做以下事情:

with open('/home/sam/Lean/Launcher/bin/Debug/config.json', 'r') as f:
        config_data=json.load(f)

但是这会在 json.load(f) 命令处崩溃,因为文件 f 中有注释。

我认为这将是一个常见问题,但我找不到太多在线 RE 如何在 python 中处理它。有人建议 commentjson 但这使我的脚本崩溃说

ImportError: cannot import name 'dump'

当我导入commentjson时

想法?

编辑: 这是我必须处理的 json 文件的片段。

{
  // this configuration file works by first loading all top-level
  // configuration items and then will load the specified environment
  // on top, this provides a layering affect. environment names can be
  // anything, and just require definition in this file. There's
  // two predefined environments, 'backtesting' and 'live', feel free
  // to add more!

  "environment": "backtesting",// "live-paper", "backtesting", "live-interactive", "live-interactive-iqfeed"

  // algorithm class selector
  "algorithm-type-name": "BasicTemplateAlgorithm",

  // Algorithm language selector - options CSharp, FSharp, VisualBasic, Python, Java
  "algorithm-language": "CSharp"
}

最佳答案

切换到json5JSON 5是一个非常小的 JSON 超集,支持注释和一些您可以忽略的其他功能。

import json5 as json
# and the rest is the same

它是测试版,速度较慢,但​​如果您只需要在启动程序时读取一些简短的配置,这可能可以考虑作为一个选项。切换到另一个标准比不遵循任何标准更好。

关于python - 如何使用 python 处理读取其中有注释的 .json 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46317639/

相关文章:

python - 是否有 pandas 函数可以比较每行中的不同列值?

python - 如何使用 rest_framework 和 Django 获取多个对象的响应

python - 使用 xarray 导入时,netCDF 文件在 python 中没有变量

python - Numpy 中的时间戳

javascript - JSON 编码 Flask 到 Javascript

C#反序列化Json数组不带[]

java - 使用 Json 实时搜索 MySQL 数据库并在 ListView android 中显示结果

python - 加载预训练模型会抛出 ValueError : bad marshal data (unknown type code)

java - 从 JSON 中获取数据不会以列表形式返回数据。进度条一直在跑

java - 根据 Java 中的 Swagger 定义验证 JSON 消息