我正在寻找一个简单的脚本来将 JSON 对象转换为 Javascript 对象,特别是能够在 jQuery 中进行 ajax 调用,然后将所有返回的 JSON 转换为 Javascript 对象。
我在 KnockOut.js 中使用了映射插件:https://github.com/SteveSanderson/knockout.mapping/tree/master/build/output
这很好地获取了我的 JSON 结果并在淘汰赛中创建了相关对象。
目前有什么可以在不淘汰的情况下做到这一点吗?
jquery 会自动为您完成此操作。
来自 getJSON 的 JQuery 文档:
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
只需在
dataType
调用中将 'json'
设置指定为 $.ajax
,或使用 $.getJSON
方法,JSON 结果将自动解析为 Javascript 对象。
document.addEventListener("DOMContentLoaded", getProducts);
function getProducts() {
fetch('https://dummyjson.com/products')
.then(res => res.json())
.then(data => loadTable(data.products));
document.getElementById("searchBtn").addEventListener("click", search);
document.getElementById("close").addEventListener("click", closeModal);
}
function loadTable(data) {
const tbody = document.querySelector("#products tbody");
tbody.innerHTML = "";
data.forEach(row => {
const newRow = tbody.insertRow();
newRow.insertCell().textContent = row.id;
newRow.insertCell().textContent = row.title;
newRow.insertCell().textContent = row.price;
newRow.insertCell().textContent = row.stock;
newRow.addEventListener("click", () => {
fetch(https://dummyjson.com/products/${row.id})
.then(res => res.json())
.then(data => {
document.getElementById("description").innerText = data.description;
openModal();
});
});
});
}
function search() {
const text = document.getElementById("searchText").value;
fetch(https://dummyjson.com/products/search?q=${text})
.then(res => res.json())
.then(data => loadTable(data.products));
}
function openModal() {
$("#modal").show();
}
function closeModal() {
$("#modal").hide();
}
我在这里猜测,但如果你想将它们转换为已经定义的 JavaScript 对象,你需要
JSON.parse
函数中的第二个参数。 查看 MDN 的文档 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/parse。JSON.parse(json,function(prop,val){
if(prop==='objName'){
new myObj(val);
}
});
在 JQUERY 中使用:http://api.jquery.com/jQuery.parseJSON/ 用于简单的 JS:https://github.com/douglascrockford/JSON-js(查看 json.js 或 json2.js)
知道它的格式良好:
var myObject = eval('(' + myJSONtext + ')');