N
N
Naboska2019-07-12 10:42:41
JavaScript
Naboska, 2019-07-12 10:42:41

How to universally parse json into blocks using jquery?

Good afternoon.

There is a page that is formed by the view:

<span data-jsonItem="key1" data-jsonValue="val">error</span>
<span data-jsonItem="key1" data-jsonValue="val2">error</span>
<span data-jsonItem="key2" data-jsonValue="val">error</span>
<span data-jsonItem="key2" data-jsonValue="val2">error</span>


Forming from json using jquery

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);
                });
            });
        }
    });
  });
}


json itself:

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


Tell me how to improve the script to universally get data-jsonItem from the html block in js and iterate over it depending on the keys that exist in it?

Right now I can only make a few conditions out of if (item == jsonItem), equating jsonItem to a key in json.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FrontJS, 2019-07-12
@frontjs

$(document).ready(function() {
  var result = data['items'];
  var oE = $(""); // ID блока
  if (oE.length == 0) oE = null;
  $.each(data['items'], function(index, value) {
    oE.append($(' ')); // Суда упакуй то что хочешь вывести в html
  });
});

And do not forget to add a key to json that will keep all these keys in itself, for example, items. Get data from the keys value.val, value.val2, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question