Разбор JSON для таблицы по месяцам с Javascript - PullRequest
0 голосов
/ 03 сентября 2018

У меня проблема с анализом объекта JSON в HTML-таблице. В основном мои данные JSON [EDITED] выглядят так:

[  
   {  
      'category': 'Automotive (Motor)',
      'month':8,
      'month_now':'Aug',
      'year':2018,
      'lists':{  
         'total':1,
         'price':591600
      }
   },
   {  
      'category': 'Health',
      'month_now':'Aug',
      'month':8,
      'year':2018,
      'lists':{  
         'total':21,
         'price':14448600
      }
   }
]

Я хочу создать такую ​​таблицу:

Я хочу добавить месяцы, начинающиеся с января по декабрь, с нулевыми данными, если у каждого месяца нет общего значения.

Я много читал о формате JSON, мои знания очень ограничены, и мне нужна помощь -__-

Я пытался, вот мой код:

$(document).ready(function () {

    var json = [{'category': Automotive (Motor),'month': 8, 'month_now': 'Aug', 'year': 2018, 'lists': {'total': 1, 'price': 591600}}, {'category': Health, 'month_now': 'Aug', 'month': 8, 'year': 2018, 'lists': {'total': 21, 'price': 14448600}}];
    var tr;
    for (var i = 0; i < json.length; i++) {
        tr = $('<tr/>');
        tr.append("<td>" + json[i].category + "</td>");
        tr.append("<td>" + json[i].month + "</td>");
        tr.append("<td>" + json[i].lists + "</td>");
        $('table').append(tr);
    }
});

Вот HTML:

<table>
    <tr>
        <th>Category</th>
        <th>Month</th>
        <th>Total</th>
    </tr>
</table>

Ответы [ 3 ]

0 голосов
/ 03 сентября 2018

Основная причина:

Ваш json недействителен. Пожалуйста, сначала убедитесь, что у вас есть действующий JSON. Вы можете использовать любой онлайн-инструмент для проверки вашего JSON.

Ключ

category имеет строковое значение, поэтому значение должно быть в кавычках. Кроме того, json[i].lists необходимо изменить на json[i].lists.total. Ниже работает демоверсия:

$(document).ready(function() {

  var json = [{
    'category': 'Automotive(Motor)',
    'month': 8,
    'month_now': 'Aug',
    'year': 2018,
    'lists': {
      'total': 1,
      'price': 591600
    }
  }, {
    'category': 'Health',
    'month_now': 'Aug',
    'month': 8,
    'year': 2018,
    'lists': {
      'total': 21,
      'price': 14448600
    }
  }];
  var tr;
  for (var i = 0; i < json.length; i++) {
    tr = $('<tr/>');
    tr.append("<td>" + json[i].category + "</td>");
    tr.append("<td>" + json[i].month + "</td>");
    tr.append("<td>" + json[i].lists.total + "</td>");
    $('table').append(tr);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <th>Category</th>
    <th>Month</th>
    <th>Total</th>
  </tr>
</table>
0 голосов
/ 06 сентября 2018

@ Zzet ответ было отлично, это всего лишь одно изменение

$(document).ready(function() {
  var json = [{
    'category': 'Automotive (Motor)',
    'month': 8,
    'month_now': 'Aug',
    'year': 2018,
    'lists': {
      'total': 1,
      'price': 591600
    }
  }, {
    'category': 'Health',
    'month_now': 'Aug',
    'month': 8,
    'year': 2018,
    'lists': {
      'total': 21,
      'price': 14448600
    }
  }];

  var tr;
  for (var i = 0; i < json.length; i++) {
    tr = $('<tr/>');
    for (var ii = 0; ii < 12; ii++) {
      tr.append($('<td>0</td>'));
    }

    tr.find('td:eq(0)').html(json[i].category);
    tr.find('td:eq('+json[i].month+')').html(json[i].lists.total);
    
    $('table').append(tr);
  }
});
table {
  width: 100%;
  text-align: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <th>Unit</th>
    <th>J</th>
    <th>F</th>
    <th>M</th>
    <th>A</th>
    <th>M</th>
    <th>J</th>
    <th>J</th>
    <th>A</th>
    <th>S</th>
    <th>O</th>
    <th>N</th>
    <th>D</th>
  </tr>
</table>
0 голосов
/ 03 сентября 2018
  1. Вы должны заключать свои категории в кавычки.
  2. Получить свойство total из объекта списков

$(document).ready(function() {
  var json = [{
    'category': 'Automotive (Motor)',
    'month': 8,
    'month_now': 'Aug',
    'year': 2018,
    'lists': {
      'total': 1,
      'price': 591600
    }
  }, {
    'category': 'Health',
    'month_now': 'Aug',
    'month': 8,
    'year': 2018,
    'lists': {
      'total': 21,
      'price': 14448600
    }
  }];

  var tr;
  for (var i = 0; i < json.length; i++) {
    tr = $('<tr/>');
    for (var ii = 0; ii < 12; ii++) {
      tr.append($('<td>'));
    }

    tr.find('td:eq(0)').html(json[i].category);
    tr.find('td:eq('+json[i].month+')').html(json[i].lists.total);
    
    $('table').append(tr);
  }
});
table {
  width: 100%;
  text-align: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <th>Unit</th>
    <th>J</th>
    <th>F</th>
    <th>M</th>
    <th>A</th>
    <th>M</th>
    <th>J</th>
    <th>J</th>
    <th>A</th>
    <th>S</th>
    <th>O</th>
    <th>N</th>
    <th>D</th>
  </tr>
</table>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...