I have an array that I need to format using JSON Stringify. I am using the Chakra UI component to display the text but it doesnt show correctly in the component. In the console it is showing how I want it however. This is the formatted text:
[
{
"price": "15.99",
"size": "m"
},
{
"price": "2.99",
"size": "s"
}
]
This is how I use it in the component:
<Code children={JSON.stringify(data, null, 2)} />
But running the app in the component it shows:
[ { "price": "15.99", "size": "m" }, { "price": "2.99", "size": "s" } ]
With no line breaks. Ive tried wrapping the JSON.stringify term in a p tag but didnt work. Not sure if there is a trick to this or a property in the code css that cuts off the lines
Your use of JSON.stringify() is correct. Yet you have to set the container to display those linebreaks.
const data = [
{
"price": "15.99",
"size": "m"
},
{
"price": "2.99",
"size": "s"
}
]
document.querySelector('p').textContent = JSON.stringify(data, null, 2)
p{
white-space: pre
}
<p>
</p>
As @CherryDT commented, you just need to use the correct element to display the JSON output, and <pre> is best suited, unless you use CSS to alter the behaviour of another element.
const data = [
{
"price": "15.99",
"size": "m"
},
{
"price": "2.99",
"size": "s"
}
];
const element = document.getElementById(`app`);
element.innerHTML = JSON.stringify(data, null, 2);
<pre id="app"></pre>