【问题标题】:Construct JSON in proper format with Jquery使用 Jquery 以适当的格式构造 JSON
【发布时间】:2015-03-17 08:26:24
【问题描述】:

我正在尝试将动态创建的 JSON 输出重新格式化为 x-editable 选择类型 source[] 可以使用的格式。我需要帮助构建数组,以便重新格式化的 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,显示此处的输出。

【问题讨论】:

  • "name" : this[0] ?
  • 谢谢,它确实有帮助,但名称值仍然被引用。公平地说,我需要更新 JSfiddle。请再看一遍...
  • 嗯,是的,它被引用是因为它是一个字符串。您不能在不破坏 json 的情况下取消引用它们。如果你想要{ value : 0 , name : Aircraft Overview } 你就完蛋了,这是无效的。

标签: javascript jquery json x-editable


【解决方案1】:

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

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

FIDDLE

【讨论】:

  • 谢谢。这有所帮助,但名称值仍被引用。有没有办法使用 eval() 删除带引号的名称和值属性。我更新了 mu FIDDLE 以反映。
  • 删除引号的用例是什么,根据 joson 规范tools.ietf.org/html/rfc4627,如果要用作 JSON,最好保留引号
【解决方案2】:

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

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 我希望这可以帮助别人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    相关资源
    最近更新 更多