如何在python中比较json与模式?

时间:2018-04-03 10:32:22

标签: python json python-jsonschema

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是包含其他变量的变量? 抱歉我的英文。

1 个答案:

答案 0 :(得分: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)