-
Notifications
You must be signed in to change notification settings - Fork 367
LSP: Support for JSON and YAML
The CUE LSP server (see the Getting Started Guide) has support for applying schemas to JSON and YAML files. This means that if your editor is configured to do so, it can use the CUE LSP server to offer completions ("intellisense") from your CUE schema, when editing JSON etc.
In this example, we're going to create a schema in CUE and apply it to a JSON file. We will then be able to see completions for field names from the schema when editing the JSON file.
We need to make sure we're working within a cue module:
embeddemo $> cue mod initThis is needed because embed attributes are only supported for CUE packages within modules.
We need a cue file which declares our schema, and links it to our JSON file. So in schema.cue we have:
@extern(embed)
package example
#schema: {
name: string
age: int & >=0
address: string
}
data: [...#schema] @embed(file=data.json)This says that the field data is a list, and every item in the list must unify with #schema, and the list as a whole must unify with data.json
So now in our editor we open data.json:
[
{
}
]If in your editor you place your cursor within that inner object, and your editor is configured to use the CUE LSP for JSON files, then if you ask your editor for completions, you should get offered the fields from #schema: "name", "age" and "address".
Note that in general this process is very sensitive to the exist JSON (or YAML) being parsable. If your typing creates invalid JSON, for example (which is extremely frequent when typing), then parsing may fail, and at that point no completions are offered. For example, an opening " which happens when you start a new field, will mean the whole file is unparsable. For this reason, ask for completions without typing the opening ".
The library we are currently using for parsing YAML is even more sensitive to this problem, so applying schemas to YAML files in this way may be less successful. We are actively working to improve this situation.