Skip to content

Instantly share code, notes, and snippets.

@lornatumuhairwe
Last active March 12, 2020 14:15
Show Gist options
  • Save lornatumuhairwe/2778b8936b3f250923d6b20a4a0b63d4 to your computer and use it in GitHub Desktop.
Save lornatumuhairwe/2778b8936b3f250923d6b20a4a0b63d4 to your computer and use it in GitHub Desktop.
Examples on usage of ex_json_schema
"""ex_json_schema validates json but first, convert it to a map.
The schema is the structure you expect the json to have.
You can setup a schema by passing your desired structure through `ExJsonSchema.Schema.resolve` method"""
schema = %{"type" => "object"} |> ExJsonSchema.Schema.validate()
# Validate using ExJsonSchema.Validator.validate method
ExJsonSchema.Validator.validate(schema, %{})
:ok
ExJsonSchema.Validator.validate(schema, "123")
{:error, [{"Type mismatch. Expected Object but got String.", "#"}]}
"""Schema definition
The "type" key is used to determine the type expected in a section of the json.
Examples of types,
1. object
2. string
3. integer
4. array
The "properties" key is used to used to define the structure the json contains.
"""
# A schema that defines a person
schema = %{
"type" => "object",
"properties" => %{
"name" => %{"type" => "string"}
}
} |> ExJsonSchema.Schema.resolve()
#This schema will validate any valid object
ExJsonSchema.Validator.validate(schema, %{})
:ok
ExJsonSchema.Validator.validate(schema, %{"name" => "Lorna"})
:ok
#But if you want to make sure the name key exists, use the `required` key
schema = %{
"type" => "object",
"required" => ["name"],
"properties" => %{
"name" => %{"type" => "string"}
}
} |> ExJsonSchema.Schema.resolve()
ExJsonSchema.Validator.validate(schema, %{})
{:error, [{"Required property name was not present.", "#"}]}
ExJsonSchema.Validator.validate(schema, %{"name" => "Lorna"})
:ok
# you can validate json nested in another json, specifying all the properties you need, if they are required or not.
schema = %{
"definitions" => %{
"kids" => %{
"type" => "object",
"properties" => %{
"name" => %{"type" => "string"}
}
}
},
"type" => "object",
"required" => ["name"],
"properties" => %{
"name" => %{
"type" => "string"
},
"nieces" => %{
"type" => "array",
"items" => %{"$ref" => "#/definitions/kids"}
}
}
} |> ExJsonSchema.Schema.resolve()
person = %{
"name" => "Lorna",
"nephews" => [
%{"name" => "X"},
%{"name" => "Y"},
%{"name" => "Z"}
],
"nieces" => [%{"name" => "A"}]
}
ExJsonSchema.Validator.validate(schema, person)
:ok
# Any corrections and contributions are welcome!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment