How to indent in JSON format

Asked

Viewed 281 times

0

I am layman still in language, I wanted JSON to be indented.

I have the text on one line:

[{"titulo":"teste","detalhes":"teste"}]

I wanted it this way:

[
    {
        "titulo": "teste",
        "detalhes": "teste1"
    }
]

That is the code:

var json = [];
    json.push({
        titulo: document.getElementById('iptTitulo').value,
        detalhes: document.getElementById('iptDetalhes').value
    });

document.getElementById('text-area').value = JSON.stringify(json);
  • And where is this JSON? What are you doing with it? How are you displaying?

  • @Andersoncarloswoss posted code

  • 2

    It would be something like JSON.stringify(json, null, '\t') what you need?

  • @Andersoncarloswoss himself, thanks. It worked!

1 answer

3


To display your JSON indented, simply use the third parameter of JSON.stringify, who receives a string which will be used for back-ups.

const json = {"userId":1,"id":1,"title":"delectus aut autem","completed":false};

console.log(JSON.stringify(json, null, '····'));

If you pass the third parameter as an integer, it will represent the amount of whitespace used in the indentation.

const json = {"userId":1,"id":1,"title":"delectus aut autem","completed":false};

console.log(JSON.stringify(json, null, 4));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.