Home > Back-end >  How to parse and form a json with a nested array?
How to parse and form a json with a nested array?

Time:06-06

I need advice and help. I have a code with which I receive data from the table in json format, so that I can then send it via ajax to the server

for (var i = 1, row; row = table.rows[i]; i  ) {
    let docDate = document.querySelector('input[name="invoice-date"]').value
    let docContragent = document.querySelector('select').value
    // ITEMS
    let name = row.cells[1].querySelector('span').dataset.id
    let quantity = row.cells[2].querySelector('input').value
    let buy_price = row.cells[3].querySelector('input').value
    var sell_price = row.cells[5].querySelector('input').value

    if(row == document.querySelector('.add-elements')) {
      break;
    }
   let invoice = {
    "doc_type": "capitalize",
    "date": docDate,
    "number": 98,
    "contragent_id": docContragent,
    "comment": "",
    "items": [
        {
            "product": name,
            "buy_price": buy_price,
            "sell_price": sell_price,
            "quantity": quantity
          },
        ]
      }
      let json = JSON.stringify(invoice);
      console.log(json)
    }

The problem is that there can be any number of elements in the "items" array (rows in the table) and I don't know how to implement this in javascript. And how safe is it? Maybe you know the best option for sending such data, I work with django (the only possible solution I found there was to use form sets, but it seems to me that this option will not work because of its limited customization).

I need this json output:

[
    {
        "doc_type": "capitalize",
        "date": "2022-06-04",
        "number": 1,
        "contragent_id" : 1,
        "comment": "",
        "items": [
            {
                "product": 10,
                "buy_price": "200.00",
                "sell_price": "500.00",
                "quantity": 5
            },
            {
                ...
            },
            {
                ...
            },
        ],
    }
]

The HTML of the table is added dynamically via api, with this code:

success: function (res) {
          let invoiceRow = document.querySelector(".invoice-add-table table tbody tr.add-elements").insertAdjacentHTML('beforebegin', '<tr >'  
          '<td align="right" >'  res.articul  '</td>'  
          '<td  align="left"><span data-id="'  res.id  '" title="'  res.name  '" style="text-decoration: underline; cursor: pointer;">'  res.name  '</span></td>'  
          '<td align="right" ><input name="quantity" value="'  1  '"  onkeypress="validateNum(event)" type="number"></td>'  
          '<td align="right" ><input name="last_buy_price" value="'  res.last_buy_price  '"  onkeypress="validateNumFloat(event)" type="number"></td>'  
          '<td align="right" ><input name="summ" value=""  onkeypress="validateNumFloat(event)" type="number"></td>'  
          '<td align="right" ><input name="sell_price" value="'  res.sell_price  '"  onkeypress="validateNumFloat(event)" type="number"></td>'  
          '<td align="right"><div style="display: flex;" ><span  onclick="test()" data-icon="bx:trash" style="color: white;" data-width="20"></span></div></td>' 
          '</tr>');
        },

P. s I'm sorry if there are errors in the text, I write it through google translate)

CodePudding user response:

Your loop will fill your array with all items and at the end push array with all items on your json

let items = [];
let docDate;

for (var i = 1, row; row = table.rows[i]; i  ) {
    docDate = document.querySelector('input[name="invoice-date"]').value
    let docContragent = document.querySelector('select').value
    // ITEMS
    let name = row.cells[1].querySelector('span').dataset.id
    let quantity = row.cells[2].querySelector('input').value
    let buy_price = row.cells[3].querySelector('input').value
    var sell_price = row.cells[5].querySelector('input').value

    items.push({
        "product": name,
        "buy_price": buy_price,
        "sell_price": sell_price,
        "quantity": quantity
    });

    if(row == document.querySelector('.add-elements')) {
      break;
    }
}

let invoice = {
    "doc_type": "capitalize",
    "date": docDate,
    "number": 98,
    "comment": "",
    "items": items
}
let json = JSON.stringify(invoice);
console.log(json)
  • Related