首页 > 解决方案 > 在 StreamDeckSDK 中正确解析新行上的 Json 数组

问题描述

我正在尝试获取一个 JSON 数组并显示完整的输出,但格式很好。(见注释掉的部分)不幸的是,JSON 数组返回 OBJECT 然后是它的输出。所以我通过字符串化来修复我得到的 [Object, Object] 错误。但现在一切都在一条线上。如何遍历数组并将它们放在新行上?

我遇到的第二个问题是,我无法执行您在未注释部分中注意到的 3 个相同的功能。我想result在它们之间添加一条新线。

   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)

            })
    }

更新 如果我取消注释这些部分,这就是它显示的内容。很难说,但发生了什么是,它需要替换setTitle三遍,并取最后一行。$SD.api.setTitle(context, result.EA.replace(new RegExp(' ', 'g'), '\n') + "\n" + result.EA + " ") 通过截图 在此处输入图像描述

标签: javascriptarraysjsonstreamdeck

解决方案


要从 获得格式良好的输出JSON.stringify,请提供可选参数:

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>


推荐阅读