使用 Jquery 以正确的格式构建 JSON

Construct JSON in proper format with Jquery

本文关键字:格式 构建 JSON Jquery 使用      更新时间:2023-09-26

我正在尝试将动态创建的 JSON 输出重新格式化为可由 x 可编辑的选择类型源 [] 使用的格式。我需要帮助构建数组,以便重新格式化的 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'
    }]*/
});

};

});

字符串化后,输出接近,但不起作用。它看起来像这样:

{"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);

小提琴

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

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;
     },
 });
}); 

我的小提琴我希望这可以帮助其他人。