GomuGomuNoRocket
GomuGomuNoRocket

Reputation: 839

How can CodeMirror display an 'javascript object' string with object structure

I start use code mirror, and i want to display an object with object structure.

I have a file with this content

{ property1: 'value', property2: { property3: 'value' }}

This is written in one line in .txt file.

Now i want to use code mirror so user can edit this file content. I get the file content using HTTP call and after that i have this code

        var editor = CodeMirror(document.getElementById('reportEditor'), {
            mode: { name: "javascript", json: true },
            theme: "default",
            lineNumbers: true,
            readOnly: false,
            value: JSON.stringify(response.data),
        });

This works fine, i get the content but code mirror display it in one line.

How can force Code Mirror to display this value like an object structure like

 { 
      property1: 'value', 
      property2: { 
           property3: 'value' 
      }
 }

I found on this site a very good json prettifier

Upvotes: 0

Views: 3213

Answers (3)

Niran Manandhar
Niran Manandhar

Reputation: 1107

var editor = CodeMirror(document.getElementById('reportEditor'), {
            mode: { name: "javascript", json: true },
            theme: "default",
            lineNumbers: true,
            readOnly: false,
            value: JSON.stringify(response.data,null,2),
        });

this works for me, setting replacer to null and indentation as 2 when changing the JSON to string.enter image description here

Upvotes: 0

Damodharan J
Damodharan J

Reputation: 360

Before setting the string into codemirror's editor, make sure you beautify your it for your preferred format.

eg. https://github.com/beautify-web/js-beautify

Also you can use the beautifier here http://jsbeautifier.org/

Upvotes: 0

GomuGomuNoRocket
GomuGomuNoRocket

Reputation: 839

The key was here JSON.stringify(response.data, null, "\t") now has JSON format

Upvotes: 3

Related Questions