Introduction
Validating JSON values to be of specific data types is a common need for many situations. Ensuring that the values in your JSON file are valid is essential to avoid configuration-related errors. This How-to Guide checks and ensures each value in a JSON file is the data type it’s supposed to be, using the CUE command line.
Prerequisites
- You have CUE installed
locally. This allows you to run
cue
commands
Requirements
- Using the command line or terminal
- File editing
Steps
Create a JSON file called x.json
with the following:
{
"people": {
"Gopher": {
"name": "Gopher",
"age": 12,
"address": "Mountain View"
},
"Ken": {
"name": "Ken",
"age": 21,
"address": "The Blue Sky"
}
}
}
Create a CUE file named x.cue
The following CUE creates a CUE definition that describes the data type constraints for every person.
#Person: {
name: string
age: int
address: string
}
people: [X=string]: #Person & {
name: X
}
Run the following cue
command in your terminal:
$ cue vet x.cue x.json
NOTE: cue vet
is silent when run successfully. Output will only show on error.
Add another person to your JSON data by replacing your x.json
file with the
following:
{
"people": {
"Gopher": {
"name": "Gopher",
"age": 12,
"address": "Mountain View"
},
"Ken": {
"name": "Ken",
"age": 21,
"address": "The Blue Sky"
},
"Rob": {
"name": "Rob",
"age": 42.2,
"address": "CUEtopia"
}
}
}
Validate again with cue vet
:
$ cue vet x.cue x.json
people.Rob.age: conflicting values 42.2 and int (mismatched types float and int):
./x.cue:3:11
./x.cue:7:21
./x.json:15:20
The command output shows validation errors where the JSON violates the (type) constraints that you have declared.
Fix up the JSON:
{
"people": {
"Gopher": {
"name": "Gopher",
"age": 12,
"address": "Mountain View"
},
"Ken": {
"name": "Ken",
"age": 21,
"address": "The Blue Sky"
},
"Rob": {
"name": "Rob",
"age": 42,
"address": "CUEtopia"
}
}
}
Validate with cue vet
again
$ cue vet x.cue x.json
The cue vet
command will show no output on success.
Well done! Any future data errors on names, ages, and addresses in your JSON will be detected. This is especially helpful with JSON files with 100s (and even 1000s) of lines.