有没有办法在 Python 中解析我的世界命令样式 JSON?

扎眼的阳光 python 193

原文标题Is there a way to parse minecraft command style JSON in Python?

Minecraft 的 JSON 解析非常松散。 Minecraft 认为 OK 的 JSON 不能被解析为有效的 JSON,也不能被解析为 YAML,也不能被直接评估为 Python 代码。

Minecraft 可以很好解析的 JSON 犯罪包括:

  1. 允许单引号 ‘ 而不是双引号 ” 。(因此不需要转义单引号内的双引号。)
  2. 允许不带引号的键
  3. 允许不带引号的字符串值。

因此,Minecraft 认为以下内容有效:{foo:bar,'foo2':'bar "foobar"'}

除了编写我自己的解析器之外,是否有任何简单的方法可以诱使 python 将其解码为字典?

原文链接:https://stackoverflow.com//questions/71462419/is-there-a-way-to-parse-minecraft-command-style-json-in-python

回复

我来回复
  • MeisterEder7的头像
    MeisterEder7 评论

    要使用包含'"的字符串变量,您需要在 Python 中使用三重双引号。然后您可以删除所有引号,然后使用正则表达式再次用"引号包裹所有部分。

    import re
    datastr = r"""{foo:bar, 'foo2':'bar "foobar"', 'foo3':"bar 'foobar' "barfoo"}"""
    
    # remove all quotes
    datastr = datastr.replace("'", "")
    datastr = datastr.replace('"', '')
    datastr = datastr.replace(", ", ",")
    # >> datastr is now {foo:bar,foo2:bar foobar,foo3:bar foobar barfoo}
    
    # wrap parts with quotes
    datastr = re.sub(r"([\w|\s]+):([\w|\s]+)", r'"\1":"\2"', datastr)
    # >> datastr is now {"foo":"bar","foo2":"bar foobar","foo3":"bar foobar barfoo"}
    

    这涵盖了您提到的所有可能性(以及更多,因为它还可以修复 json 键中的不规则/空白/引号)。如果这不适用于整个数据集,也许看看像 https://pypi.org/ 这样的包项目/demjson/

    2年前 0条评论