如何在 codemirror 上显示 JSON?

how to show JSON on codemirror?

目前我正在使用 ngx-codemirror - codemirror 上的 angular 包装器。

在我的应用程序中

html 如图所示

<ngx-codemirror [(ngModel)]="data" [autoFocus]=true [options]="{lineNumbers: true,theme: 'material',mode: 'markdown'}"></ngx-codemirror>

如节目所示

data='';
   json = {
        "title": "Type",
        "description": "A type of product",
        "type": "object"
  };

constructor(){
      this.data = JSON.stringify(this.json);
}

它在单行中正确显示 json 文本,但我想以 json 格式而不是单行中的字符串显示它。

我该怎么做?

您可以在 JSON.stringify() 方法中发送一个空的白色 space 字符作为 space 参数。尝试以下

控制器

data = '';
json = {
  "title": "Type",
  "description": "A type of product",
  "type": "object"
};

ngOnInit() {
  this.data = JSON.stringify(this.json, null, ' ');    // <-- string literal ' ' as `space` argument  
}

您也可以通过发送数字来修改缩进 space。例如。 JSON.stringify(this.json, null, 4)表示缩进4space秒。

模板

<ngx-codemirror #codemirror
  [options]="codeMirrorOptions"
  [(ngModel)]="data"
  (ngModelChange)="setEditorContent($event)">
</ngx-codemirror>

工作示例:Stackblitz