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

som*_*ode 11 python json

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

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

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

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

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

ImportError: cannot import name 'dump'
Run Code Online (Sandbox Code Playgroud)

当我导入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"
}
Run Code Online (Sandbox Code Playgroud)

h22*_*h22 12

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

import json5 as json
# and the rest is the same
Run Code Online (Sandbox Code Playgroud)

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

  • 该模块是否包含在标准库中?如果有,是什么版本? (2认同)

Jea*_*bre 5

一种 hack(因为如果//json 数据中有,那么它将失败),但对于大多数情况来说足够简单:

import json,re

s = """{
  // 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"
}
"""

result = json.loads(re.sub("//.*","",s,flags=re.MULTILINE))

print(result)
Run Code Online (Sandbox Code Playgroud)

给出:

{'environment': 'backtesting', 'algorithm-type-name': 'BasicTemplateAlgorithm', 'algorithm-language': 'CSharp'}
Run Code Online (Sandbox Code Playgroud)

将正则表达式应用于所有行,删除双斜杠及其后面的所有内容。

也许解析该行的状态机会更好地确保它们//不在引号中,但这稍微复杂一些(但可行)

  • 好的,但是如果第一行以“//”开头,那么对于带有空格的第一行将不起作用。像“^|\s”之类的东西,但是你必须分组并且不要捕获。那好吧... (2认同)