4

I am writing a software that can read the JSON data from a file. The file contains "person" - an object whose value is an array of objects. I am planning to use a JSON schema validating libraries to validate the contents instead of writing the code myself. What is the correct schema that conforms to JSON Schema Draf-4 which represents the below data?

{
   "person" : [
      {
         "name" : "aaa",
         "age"  : 10
      },
      {
         "name" : "ddd",
         "age"  : 11
      },
      {
         "name" : "ccc",
         "age"  : 12
      }
   ]
}

The schema that wrote down is given below. I am not sure whether it is correct or is there any other form?

{
   "person" : {
      "type" : "object",
      "properties" : {
         "type" : "array",
         "items" : {
            "type" : "object",
            "properties" : {
               "name" : {"type" : "string"},
               "age" : {"type" : "integer"}
            }
         }
      }
   }
}

1 Answer 1

3

You actually only have one line in the wrong place, but that one line breaks the whole schema. "person" is a property of the object and thus must be under the properties keyword. By putting "person" at the top, JSON Schema interprets it as a keyword instead of a property name. Since there is no person keyword, JSON Schema ignores it and everything below it. Therefore, it is the same as validating against the empty schema {} which places no restrictions on what a JSON document can contain. Any valid JSON is valid against the empty schema.

{
   "type" : "object",
   "properties" : {
      "person" : {
         "type" : "array",
         "items": {
            "type" : "object",
            "properties" : {
               "name" : {"type" : "string"}
               "age" : {"type" : "integer"}
            }
         }
      }
   }
}

By the way, there are several online JSON Schema testing tools out there that can help you out when crafting your schemas. This one is my goto http://jsonschemalint.com/draft4/#

Also, here is a great JSON Schema reference that might help you out as well: https://spacetelescope.github.io/understanding-json-schema/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.