Home

cuesonnet @ad92adf766ccabb211e2344123f01dcf37636f22 - refs - log -
-
https://git.jolheiser.com/cuesonnet.git
CUE + Jsonnet
cuesonnet / README.md
- raw -
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# cuesonnet

Validate [Jsonnet](https://jsonnet.org/) data against [CUE](https://cuelang.org/) constraints.

## Usage

[Example Schema](testdata/person/schema.cue)

```cue
import "time"

#Schema: {
	// Basic schema
	firstName: string
	lastName:  string
	age:       int
	birthday:  string

	// Refine as needed
	#Title:    =~"^[A-Z]" | error("must start with an uppercase letter")
	firstName: #Title
	lastName:  #Title
	age:       >0
	birthday:  time.Format("01/02/2006")

	// Defaults
	gopher: bool | *true
}

// Apply the schema to root
#Schema
```

[Example Jsonnet](testdata/person/valid.jsonnet)

```jsonnet
{
  firstName: 'Jim',
  lastName: 'Jimbly',
  age: 45,
  birthday: '01/02/2003',
}
```

Embedding the schema is the recommended pattern:

```go
//go:embed schema.cue
var schema cuesonnet.Schema

var result MyStruct
if err := schema.Decode(r, &result); err != nil {
    // handle validation errors
}
```

## Schema notes

**Human-readable errors:** CUE constraint errors surface raw expressions by default (e.g. `out of bound =~"..."`). Use `| error("message")` in your schema to replace them with plain language - see `#Title` in the example above.

**`float` vs `number`:** JSON has one number type. go-jsonnet serializes `50.0` as `50`, which CUE treats as `int` and rejects against `float`. Use `number` for fields that should accept whole-number values; reserve `float` only when integers must be rejected.

## Tests

`testdata/` contains a large list of schemas and Jsonnet fixtures covering CUE features (types, constraints, structs, lists, disjunctions, defaults, definitions, composition, stdlib) and Jsonnet features (functions, comprehensions, conditionals, inheritance, multiline strings, self-reference, stdlib).
See `cuesonnet_test.go` and `cuesonnet_decode_test.go`.

## License

[MIT](LICENSE)