如何普遍解析json以从html块[data-json Item]中获取并将密钥插入其中?
我的html,包含data-jsonItem(json-key,key2)和data-jsonValue(json-subObject):
<span data-jsonItem="key1" data-jsonValue="val"></span>
<span data-jsonItem="key1" data-jsonValue="val2"></span>
<span data-jsonItem="key2" data-jsonValue="val"></span>
<span data-jsonItem="key2" data-jsonValue="val2"></span>
我的JavaScript
<script>
function jsonUPDATE() {
var URL = "/json.json";
$.getJSON(URL, function(data){
$.each(data, function (item, value) {
var jsonItem = "key1";
if (item == jsonItem) {
$.each(value, function (i, object) {
$.each(object, function (subI, subObject) {
$("[data-jsonValue='"+subI+"']").html(subObject);
});
});
}
});
});
}
</script>
json:
{
"key1": [
{
"val": 0,
"val2": 0,
"val3": 0,
}
],
"key2": [
{
"val": 0,
"val2": 0,
"val3": 0,
}
]
}
答案 0 :(得分:1)
代替遍历对象数组中的所有项目,您可以提高逻辑的效率,并使逻辑更加简洁,方法是遍历所有span
元素并根据以下内容直接从对象中检索数据:该data
上的span
属性。试试这个:
var data = {
"key1": [{
"val": 1,
"val2": 2,
"val3": 3,
}],
"key2": [{
"val": 4,
"val2": 5,
"val3": 6,
}]
}
// in your AJAX callback:
$('span').html(function() {
var $span = $(this)
return data[$span.data('jsonitem')][0][$span.data('jsonvalue')];
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-jsonItem="key1" data-jsonValue="val"></span>
<span data-jsonItem="key1" data-jsonValue="val2"></span>
<span data-jsonItem="key2" data-jsonValue="val"></span>
<span data-jsonItem="key2" data-jsonValue="val2"></span>
请注意,我更改了对象中的valX
值,以使此逻辑的效果更加清晰。