Check JSON syntax using language pack

I’ve wrapped CodeMirror6 in an Angular ControlValueAccessor, discussed in ControlValueAccessor - string concatenation, and the code is on GitHub.

I would like to detect errors in real-time. Based on recommendations in ControlValueAccessor - string concatenation, I avoid calling toString until I definitely need the value.

I could detect value changes, call toString and use a function like this to catching syntax errors:

function IsJson(value: any): boolean {
  try {
    JSON.parse(value);
    return true;
  } catch {
    return false;
  }
}

However, this would involve calling toString on large documents, every time the form value changes. This I think, is out of the question.

Is there any way the syntax can be checked using the JSON language pack?

Yes, if you iterate through the the syntax tree for nodes marked as errors, that could give you the location of parse errors, though it doesn’t provide you with any error message or anything like that.

1 Like

That sounds like what I’m looking for. Although I guess there’s no way to get the text from syntax tree?

No, the editor doesn’t store the entire document as a flat string anywhere (for precisely the efficiency reasons you mention).

Thanks. This is proving more difficult than I thought it would be. I’ve got the tree and a cursor to iterate over it. But it’s not clear how a SyntaxNode is marked as having an error.

// cm is EditorView
const tree: Tree = syntaxTree(cm.state);
const cursor: TreeCursor = this.tree.cursor();
while (cursor.next()) {
   const sn: SyntaxNode = cursor.node;
   const nt: NodeType = sn.type;
   if (nt.isError) {
      // syntax error!
    }
}

I went with TreeCursor based on the advice in Lezer Reference Manual

What is not clear about it? Your code looks correct.

Ugh. Apologies. I was only getting the syntax tree in the constructor, and not on each call to validate the form control. It’s all working. Thanks for your support. I’ll update the public repo with this.