在 Sublime Text 3 中查找重复的 JSON 键

Find Duplicate JSON Keys in Sublime Text 3

我有一个 JSON 文件,目前,在投入生产之前手动验证该文件。理想情况下,这是一个自动化过程,但目前这是限制条件。

我发现在 Eclipse 中有用的一件事是 JSON 工具,它可以突出显示 JSON 文件中的重复键。在 Sublime Text 中或通过插件是否有类似的功能?

例如,以下 JSON 可能会产生有关重复键的警告。

{
    "a": 1,
    "b": 2,
    "c": 3,
    "a": 4,
    "d": 5
}

谢谢!

plenty of JSON validators available online. I just tried this one and it picked out the duplicate key right away. The problem with using Sublime-based JSON linters like JSONLint is that they use Python's json个模块,多键不报错:

import json
json_str = """
{
    "a": 1,
    "b": 2,
    "c": 3,
    "a": 4,
    "d": 5
}"""
py_data = json.loads(json_str) # changes JSON into a Python dict
                               # which is unordered
print(py_data)

产量

{'c': 3, 'b': 2, 'a': 4, 'd': 5}

显示第一个 a 密钥被第二个覆盖。因此,您需要另一个非 Python 基础的工具。

甚至 Python 文档也说:

The RFC specifies that the names within a JSON object should be unique, but does not mandate how repeated names in JSON objects should be handled. By default, this module does not raise an exception; instead, it ignores all but the last name-value pair for a given name:

weird_json = '{"x": 1, "x": 2, "x": 3}' json.loads(weird_json) {'x': 3}

object_pairs_hook 参数可用于改变此行为。

正如文档所指出的那样:

class JsonUniqueKeysChecker:
    def __init__(self):
        self.keys = []

    def check(self, pairs):
        for key, _value in pairs:
            if key in self.keys:
                raise ValueError("Non unique Json key: '%s'" % key)
            else:
                self.keys.append(key)
        return pairs

然后: c = JsonUniqueKeysChecker() print(json.loads(json_str, object_pairs_hook=c.check)) # raises

JSON 是非常简单的格式,不是很详细所以这样的事情会很痛苦。检测双键很容易,但我敢打赌从中伪造插件需要大量工作。