用 Jquery 以正确的格式构建 JSON

Construct JSON in proper format with Jquery

我正在尝试将动态创建的 JSON 输出重新格式化为 x-editable select 类型源[] 可以使用的格式。我需要构建数组的帮助,以便重新格式化的 JSON 输出如下所示:

{value: 2, name: 'Maintenance'},

下面是我正在消费的原始示例 JSON:

{"COLUMNS":["SECTIONCOMMONNAME"],"DATA":[["Aircraft Overview"],["Email Server Settings"],["Maintenance"],["Page Sections"],["WOW"]]}

我使用的代码是:

$(document).ready(function () {
var myURL = 'https://api.myjson.com/bins/3nzdj';
var myarray = [];

$.ajax({
    url: myURL,
    dataType: 'json',
    success: function (e) {
        console.log('My created console output:' +'<br>');
        $.each(e.DATA, function (i, jsonDataElem) {

            console.log("{value: " + i + ', ' + "name: " + '"'+this+"'}");
            var item = {
                "value": i,
                    "name": this
            };
            myarray.push(item);
        });
        var newJson = JSON.stringify(myarray);
        console.log('My stringify output:' +'<br>' +newJson);
    }
});

$('.sectionsAvailable').editable({
    name: 'template',
    type: 'select',
    placement: 'right',
    send: 'always',
    value: 1,
    source: [], //newJson (my new var)

    /* should be in this format:
     source: [{
        value: 1,
        text: 'text1'
    }, {
        value: 2,
        text: 'text2'
    }]*/

});


};

});

stringify 后,输出关闭,但不会工作。它看起来像这样:

{"value":2,"name":["Maintenance"]}

并且需要看起来像这样L

{value:2,name:'Maintenance'},

这里是 JSfiddle 显示这里的输出。

您似乎在分配完整的数组而不是索引 0 处的值试试这个

 var item = {
              "value": i,
              "name": this[0] // gives elemnt at index 0
            };
  myarray.push(item);

FIDDLE

我能够回答我自己的问题。可能有更好的方法,但这行得通:

var myURL = 'https://api.myjson.com/bins/3nzdj';
$.getJSON(myURL, function(data) {
var output = '';
  $.each(data.DATA, function(key, val) {
    output +='{value: ';
    output += "'"+key+"'";
    output +=',text:';
    output += "'"+val+"'";
    output +='}';
    output +=',';
});
    var outputAdapted = '['+output+']'
$('.sectionsAvailable').editable({
    name: 'template',
    type: 'select',
    placement: 'right',
    send: 'always',
    value: 1,
     // should be in this format:
     source: 
     function() {
      return outputAdapted;
     },
 });
}); 

我的 FIDDLE 我希望这可以帮助其他人。