简体   繁体   English

如何使用jquery将json普遍解析为块?

[英]How to universally parse json into blocks using jquery?

How to universally parse json to get from the html block [data-json Item], and insert the key into it? 如何普遍解析json从html块[data-json Item]获取,并将密钥插入其中?

my html, contains data-jsonItem (json - key,key2) and data-jsonValue (json - subObject): 我的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>

my javascript 我的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: JSON:

{
    "key1": [
        {
            "val": 0, 
            "val2": 0, 
            "val3": 0, 
        }
    ], 
    "key2": [
        {
            "val": 0, 
            "val2": 0, 
            "val3": 0, 
        }
    ]
}

Instead of looping through all items in the array of objects you could improve the efficiency of the logic and make it more succinct by instead looping through all the span elements and retrieving the data from the object directly, based on the data attributes on that span . 而不是遍历对象数组中的所有项目,您可以提高逻辑的效率,并通过循环遍历所有span元素并根据该span上的data属性直接从对象检索数据,使其更简洁。 Try this: 尝试这个:

 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> 

Note that I changed the valX values in the objects to make the effect of this logic clearer. 请注意,我更改了对象中的valX值,以使此逻辑的效果更清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM