首先,我知道注释不是有效的 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"
}
最佳答案
切换到json5 。 JSON 5是一个非常小的 JSON 超集,支持注释和一些您可以忽略的其他功能。
import json5 as json
# and the rest is the same
它是测试版,速度较慢,但如果您只需要在启动程序时读取一些简短的配置,这可能可以考虑作为一个选项。切换到另一个标准比不遵循任何标准更好。
关于python - 如何使用 python 处理读取其中有注释的 .json 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46317639/