我正在尝试将动态创建的 JSON 输出重新格式化为 x-editable 选择类型源 [] 可以使用的格式。我需要帮助构建数组,以便重新格式化的 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);
关于javascript - 使用 Jquery 以正确的格式构建 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29094328/