1

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"
  }
}

How to check that all keys are there and their type is the same?

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() return only options and PC, but i need name, count, a1, processor, os too.

And one more question, how to know that PC and options is variable which contains another variables? Sorry for my english.

1 Answers1

0

You can use recursion with 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)
Ajax1234
  • 69,937
  • 8
  • 61
  • 102