从 Polymer 中的核心响应解析值

Parsing values from core-response in Polymer

我正在使用 Polymer 从 flax/python 后端请求 x 和 y 值,我可以在控制台中读取 XMLHttpResquest 响应的值,但现在我需要将输出转换为一个集合离散的 x 和 y 值(因此它可以被 C3.js 读取 - 一个位于 D3 顶部的框架用于绘图)。

这是我用来获取 XMLHttpResquest 响应的代码:

<paper-button affirmative hover on-tap="{{addNewGraph}}">Submit</paper-button>

Polymer("add-graphItem",{

        addNewGraph: function () {

            var HeaderName = this.$.graphOptionsLoad.$.headerValue.selectedItem.label;
            var FunctionName = this.$.graphFunctionsLoad.$.functionValue.selectedItem.label;
            console.log("The options are " +HeaderName +" and " +FunctionName);

            var params = {};
            if (this.$.graphOptionsLoad.$.headerValue.selectedItem) {
                params['DataHeader'] = this.$.graphOptionsLoad.$.headerValue.selectedItem.label;
            }
            if (this.$.graphFunctionsLoad.$.functionValue.selectedItem) {
                params['FunctionName'] = this.$.graphFunctionsLoad.$.functionValue.selectedItem.label;
            }
            this.$.sendOptions.params = JSON.stringify(params);
            var x = this.$.sendOptions.go();
            // this.$.sendOptions.go();
            console.log(x)

            // var ajax = document.querySelector("sendOptions");

            var results = [];
            this.addEventListener("core-response", 
                function(e) {
                    console.log(x.response);
                }
            );
        }
});

下面是 console.log(x.response); 的输出示例:

{
  "graph": [
    {
      "Header": "MakeModeChange"
    }, 
    {
      "x": [
        0.0, 
        131.35, 
        26971.3, 
        27044.75, 
        27351.4, 
        27404.483333333334, 
        27419.416666666668, 
        33128.96666666667, 
        33549.13333333333, 
        34049.48333333333, 
        77464.26666666666, 
        77609.71666666666, 
        174171.85, 
        259166.98333333334
      ]
    }, 
    {
      "y": [
        1, 
        2, 
        3, 
        4, 
        5, 
        6, 
        7, 
        8, 
        9, 
        10, 
        11, 
        12, 
        13, 
        14
      ]
    }
  ]
}

最终我需要输出如下所示:

['x', 0.0, 131.35, 26971.3, 27044.75, 27351.4, 27404.483333333334...],
['y', 1, 2, 3, 4, 5, 6]

这是一种快速而肮脏的方法 - 不推荐用于大规模或如果您不完全信任响应值。同样,很明显,但是如果他们的 api/data 结构发生变化,你就是 SOL。

xArr = JSON.parse(x.response).graph[1].x
xArr.unshift('x')

yArr = JSON.parse(y.response).graph[2].y
yArr.unshift('y')

你会得到你需要的两个阵列,你可以根据需要组合