P
P
Pavel2015-09-02 18:13:49
React Native
Pavel, 2015-09-02 18:13:49

How to work with json using jquery?

There is a rather non-trivial json file. With arrays as well.
It is necessary to make a dom tree from this json file with data and IDs. Yes, you can use some kind of angular or just a template engine and write something like

<ul ng-repeat="{corpus.levels.room}">
<li>{corpus.levels.room.user}</li>
</ul>


But in a particular case, there is only jQuery and no template engine. How to simplify this piece of code:

$.getJSON( "js/data.json", function( data ) {
  var items = [];
  $.each( data, function( corpus, val ) {
    $('body').append('<section class="json" data-corpus='+corpus+'>');
    $.each( data[corpus], function( key2, val2 ) {
      //console.log(key2 + ' - ' + val2);
      var section = $('section.json[data-corpus="'+corpus+'"]');
      section.append('<div class="'+key2+'-'+corpus+'">Корпус '+val2+'</div>')
      $.each( data[corpus].levels, function( key3, val3 ) {
        //console.log(key3 + ' - ' + val3);
        level = section.find('.levels-'+key3);
        $.each( data[corpus].levels[key3], function( key4, val4 ) {
            level.append('<div class="'+key4+'">'+val4+'</div>');
            $.each( data[corpus].levels[key3].rooms, function( key5, val5 ) {
                var rooms = level.find('.rooms');
                rooms.append('<div class="room" data-roomId="'+key5+'">');
                $.each( data[corpus].levels[key3].rooms[key5], function( key6, val6 ) {
                    var room = rooms.find('.room[data-roomid="'+key5+'"]');
                    room.append('<div class="'+key6+'">'+val6+'</div>');
                });
            });
        });
      });
    });
  });

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2019-03-22
@ynizhenie

Array length

N
Nikolay Marinkin, 2015-09-02
@NicoBurno

I'm unlikely to answer your question. But:
Why don't you use XML? You can also write HTML tags in it. If you don't need it, you can just mark it with a class and remove it before inserting it into the final document...
At least I would if I could influence the input.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question