最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get Table data in json format - Stack Overflow

programmeradmin3浏览0评论

Hello everyone I'm trying to get table data in json format here is my table

   <table>
  <thead>
    <tr>
      <th>srno</th>
      <th>name</th>
      <th>email</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Jhon One</td>
      <td>Doe one</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Jhon two</td>
      <td>Doe Two</td>
    </tr>
  </tbody>
</table>

<button>
  convert
</button>

the result which i am getting is this

{
    "0": {
        "1",
        "Jhon One",
        "Doe one"
    }
    ,
    "1": {
        "2",
        "Jhon two",
        "Doe Two"
    }
}

using the below javascript

$("button").click(function() {
  var json = html2json();
  alert(json);
});

function html2json() {
  var json = '{';
  var otArr = [];
  // var i = 1;
  var tbl2 = $('table tbody tr').each(function(e) {
    x = $(this).children();
    var itArr = [];
    x.each(function() {
      itArr.push('"' + $(this).text() + '"');
    });
    otArr.push('"' + e + '": {' + itArr.join(',') + '}');
  })
  json += otArr.join(",") + '}'

  return json;
}

but i want to add key to every value and the number should start from one and not zero.

i have a set of desire result and it should look like this any help is appreciated

  {
        "1": {
           no: "1",
           name:"Jhon One",
           lastname "Doe one"
        }
        ,
         "2": {
           no: "1",
           name:"Jhon two",
           lastname "Doe two"
        }

    }

here is the fiddel link which i have tried

/

Hello everyone I'm trying to get table data in json format here is my table

   <table>
  <thead>
    <tr>
      <th>srno</th>
      <th>name</th>
      <th>email</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Jhon One</td>
      <td>Doe one</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Jhon two</td>
      <td>Doe Two</td>
    </tr>
  </tbody>
</table>

<button>
  convert
</button>

the result which i am getting is this

{
    "0": {
        "1",
        "Jhon One",
        "Doe one"
    }
    ,
    "1": {
        "2",
        "Jhon two",
        "Doe Two"
    }
}

using the below javascript

$("button").click(function() {
  var json = html2json();
  alert(json);
});

function html2json() {
  var json = '{';
  var otArr = [];
  // var i = 1;
  var tbl2 = $('table tbody tr').each(function(e) {
    x = $(this).children();
    var itArr = [];
    x.each(function() {
      itArr.push('"' + $(this).text() + '"');
    });
    otArr.push('"' + e + '": {' + itArr.join(',') + '}');
  })
  json += otArr.join(",") + '}'

  return json;
}

but i want to add key to every value and the number should start from one and not zero.

i have a set of desire result and it should look like this any help is appreciated

  {
        "1": {
           no: "1",
           name:"Jhon One",
           lastname "Doe one"
        }
        ,
         "2": {
           no: "1",
           name:"Jhon two",
           lastname "Doe two"
        }

    }

here is the fiddel link which i have tried

https://jsfiddle/k228n2bn/

Share Improve this question asked Jun 2, 2017 at 17:57 ManavManav 3062 gold badges3 silver badges17 bronze badges 2
  • i hope this stackoverflow link might help you – hasan Commented Jun 2, 2017 at 18:35
  • Not a great idea to build JSON by means of string concatenation. sonicblis and Félix have done it the correct way. – Langdon Commented Jun 2, 2017 at 18:53
Add a ment  | 

4 Answers 4

Reset to default 2

Just change the following line

otArr.push('"' + e + '": {' + itArr.join(',') + '}');

to

otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}');

The parenthesis will add the values as numbers not strings.

Also, add keys array for internal object keys.

function html2json() {
   var json = '{';
   var otArr = [];
  // var i = 1;
   var tbl2 = $('table tbody tr').each(function(e) {        
      x = $(this).children();
      var itArr = [];
      var keys = ['no','name','lastname'];
      x.each(function(i) {
         itArr.push('"' + keys[i] + '":"' + $(this).text() + '"');
      });
      otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}');
   })
   json += otArr.join(",") + '}'

   return json;
}

You can convert e to a Number and add one to it like in this fiddle.

function html2json() {
  var json = '{';
  var otArr = [];
  // var i = 1;
  var tbl2 = $('table tbody tr').each(function(e) {
    x = $(this).children();
    var itArr = [];
    x.each(function() {
      itArr.push('"' + $(this).text() + '"');
    });
    otArr.push('"' + (Number(e) + 1) + '": {' + itArr.join(',') + '}');
  })
  json += otArr.join(",") + '}'

  return json;
}

The json you're returning is not valid though. You may want to do something like this fiddle if you can to simplify and ensure valid json and to create your objects from any table structure.

function html2json() {   
  var otArr = [];
  var tblHeaders = Array.from($('table thead tr')
    .children())
    .map(header => $(header).text());  
  var tbl2 = $('table tbody tr').each(function(e) {        
    const values = Array.from($(this).children());
    const row = {};
    for (let i = 0; i < tblHeaders.length; i++){        
        row[tblHeaders[i]] = $(values[i]).text();
    }
    otArr.push({
        [e+1]: row
    })      
  })
  json = JSON.stringify(otArr);  
  return json;
}

Try e+1

change otArr.push('"' + e + '": {' + itArr.join(',') + '}');

to
otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}');

$("button").click(function() {
  var json = html2json(); 
});

function html2json() {
  var json = '{';
  var otArr = [];
   
  var tbl2 = $('table tbody tr').each(function(e) {
    x = $(this).children();
    var itArr = [];
    x.each(function(e) {
   
      var items='';
       if(e == 0){
          items +='no : "'+ $(this).text()+'"';
          
       } 
       if(e == 1){
          items +='name : "' +$(this).text()+'"'; 
       }
       if(e == 2){
          items +='email : "' +$(this).text()+'"'; 
       }
       
       itArr.push(items);
       
    });
   
    otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}');
  })
  json += otArr.join(",") + '}'
alert(json);
  return json;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>srno</th>
      <th>name</th>
      <th>email</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Jhon One</td>
      <td>Doe one</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Jhon two</td>
      <td>Doe Two</td>
    </tr>
  </tbody>
</table>

<button>
  convert
</button>

Maybe you can use theads as keys for the generated objects. Check this jsfiddle.

function html2json() {
  var $table = $('table');
  var $ths = $table.find('thead>tr>th');
  var rows = {};
  $table.find('tbody>tr').each(function () {
    var row = {};
    $(this).children().each(function (index) {
      row[$ths[index].textContent] = this.textContent;
    });
    rows[row.srno] = row;
  });
  return JSON.stringify(rows);
}
发布评论

评论列表(0)

  1. 暂无评论