【问题标题】:How to compare json with pattern in python?如何将json与python中的模式进行比较?
【发布时间】:2018-09-12 15:35:50
【问题描述】:

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 是包含另一个变量的变量? 对不起我的英语。

【问题讨论】:

标签: python json python-jsonschema


【解决方案1】:

你可以使用递归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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    相关资源
    最近更新 更多