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

1

Create a JSON file called x.json with the following:

x.json
{
    "people": {
        "Gopher": {
            "name": "Gopher",
            "age": 12,
            "address": "Mountain View"
        },
        "Ken": {
            "name": "Ken",
            "age": 21,
            "address": "The Blue Sky"
        }
    }
}
2

Create a CUE file named x.cue

The following CUE creates a CUE definition that describes the data type constraints for every person.

x.cue
#Person: {
	name:    string
	age:     int
	address: string
}

people: [X=string]: #Person & {
	name: X
}
3

Run the following cue command in your terminal:

TERMINAL
$ cue vet x.cue x.json

NOTE: cue vet is silent when run successfully. Output will only show on error.

4

Add another person to your JSON data by replacing your x.json file with the following:

x.json
{
    "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"
        }
    }
}
5

Validate again with cue vet:

TERMINAL
$ 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.

6

Fix up the JSON:

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

Validate with cue vet again

TERMINAL
$ 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.

Further reading/See Also