0

I am have managed to output the JSON from an API, however it is outputted in one large block, I however wish to display each piece of json on a new line everytime there is a closing '}'.

import React, { Component } from 'react';
import './App.css';
import $ from 'jquery';

class App extends Component {

  state = {result : null}

  componentDidMount = () => {

    $.ajax({
      type: "GET",
      url: 'http://localhost:3001/data',
      data: {},
      xhrFields: {
        withCredentials: false
      },
      crossDomain: true,
      dataType: 'JSON',
      success: (result) => {
        this.setState({result : result});
      }
    });

  };

  render() {
    return (
          <div className="App">
            <header>
              <h2>Last Application Deployment </h2>
            </header>
            <div id='renderhere'>
              {JSON.stringify(this.state.result)}
            </div>
          </div>
        );
  }
    }

export default App;

2 Answers 2

4

First option: if you want to output JSON for debugging purpose, you should try react-json-pretty

Second option: if what you trying to do is supposed to be for production do something like this:

<div id='renderhere'>
  <pre>{JSON.stringify(this.state.result, null, 2)}</pre>
</div>
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer, however, I am already using JSON.stringify(), what I am trying to achieve is, instead of outputting the JSON as a whole block, I want each object in the JSON to be outputted to the browser on a new line, sorry if this wasnt clear.
Sorry, my code example was broken, please check the answer again.
That is great! Thanks.
3

try to wrap your text around this css style. and your issue will be solved. No complicated functions needed for this.

 <p style={{whiteSpace: 'pre-line'}}>my json text goes here \n\n</p>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.