1

json数据:

{
  "options": {
    "name": "aaa",
    "count": 20,
    "a1": 30
  },
  "PC": {
    "processor": "Intel",
    "os": "windows"
  }
}

图案:

{
  "options": {
    "name": "string",
    "count": "integer",
    "a1": "integer"
  },
  "PC": {
    "processor": "string",
    "os": "string"
  }
}

如何检查所有键都在那里并且它们的类型是否相同?

import json

data = '{"options": {"name": "aaa","count": 20,"a1": 30},"PC": {"processor": "Intel","os": "windows"}}'
pattern = '{"options": {"name": "string","count": "integer","a1": "integer"},"PC": {"processor": "string","os": "string"}}'
json_data = json.loads(data)
json_pattern = json.loads(pattern)

for key in json_pattern.keys():
  if key not in json_data:
      print("Error: %s" % key)

print("end")

json_pattern.keys()只返回optionsPC,但我name, count, a1, processor, os也需要。

还有一个问题,如何知道它PCoptions包含另一个变量的变量?对不起我的英语不好。

4

1 回答 1

0

您可以使用递归zip

import __builtin__ as built
testing_data = [[{"options": {"name": "aaa", "count": 20, "a1": 30}, "PC": {"processor": "Intel", "os": "windows"}}, {"options": {"name": "string","count": "integer", "a1": "integer"}, "something": {"processor": "string", "os": "string"}}]]

def check_input(a, b):
   for [c, d], [g, f] in zip(sorted(a.items(), key=lambda x:x[0]), sorted(b.items(), key=lambda x:x[0])):
      if c != g:
        raise ValueError("Wrong key. Expecting '{}', not '{}'".format(g, c))
      if not isinstance(d, dict) and not isinstance(f, dict) and not isinstance(d, getattr(built, f[:3])):
         raise TypeError("Wrong value type. Expecting '{}' for key '{}', not '{}'".format(f, g, type(d).__name__))
      if all(isinstance(i, dict) for i in [d, f]):
         check_input(d, f)

for i in testing_data:
  check_input(*i)
于 2018-04-03T14:22:14.637 回答