1

I'm trying to take a JSON Array and display the full output, but nicely formatted. (see commented out section) Unfortunately the JSON array returns back with OBJECT then its output. So I stringify to fix the [Object, Object] error I was getting. But now everything is on one line. How do iterate through the array and put them on new lines?

Second issue I'm having is, I can't do 3 of the same functions as you notice in the uncommented section. I'd like to take each result and add a new line in between them.

   function setTitleStatus(context, settings) {
        $SD.api.setTitle(context, "Updating...");
        getResults(result => resultCallback(result, context));
    }

    function resultCallback(result, context) {
        if (!result.hasOwnProperty("Object")) {
           $SD.api.setTitle(context, JSON.stringify(result));
           console.log(JSON.stringify(result, '%c%s'));
           return;
        }
        // This is where I'd like all 3 objects to be split on new lines.
        // $SD.api.setTitle(context, result.Platform.replace(new RegExp(' ', 'g'), '\n') +
        //     "\n" + result.Platform + " ")
        // $SD.api.setTitle(context, result.PU.replace(new RegExp(' ', 'g'), '\n') +
        //     "\n" + result.PU + " ")
        // $SD.api.setTitle(context, result.EA.replace(new RegExp(' ', 'g'), '\n') +
        //     "\n" + result.EA + " ")
    }

    function getResults(updateTitleFn) {
        let endPoint = "https://status.robertsspaceindustries.com/static/content/api/v0/systems.en.json";
        $.getJSON(endPoint)
            .done(function (response) {

                updateTitleFn({
                    "Platform": response[0].status,
                    "PU": response[1].status,
                    "EA": response[2].status,
                });

                console.log("Platform", response[0].status)
                console.log("PU", response[1].status)
                console.log("EA", response[2].status)

            })
    }

Update If I uncomment the sections this is what it shows. Its hard to tell but whats happening is, its taking replacing setTitle three times, and taking the last line. $SD.api.setTitle(context, result.EA.replace(new RegExp(' ', 'g'), '\n') + "\n" + result.EA + " ") Via Screenshot enter image description here

1 Answers1

1

To get nicely formatted output from JSON.stringify, supply the optional arguments:

JSON.stringify(obj, null, 2)

let arr = ["Pineapple", "Lemon", "Apple", "Orange", "Peach"];

document.getElementById('result').innerHTML =
  'Stringify default: ' + JSON.stringify(arr) + '\n\n' +
  'Stringify formatted: ' + JSON.stringify(arr, null, 2);
  
<pre id="result"></pre>
terrymorse
  • 6,771
  • 1
  • 21
  • 27