在javascript中以特定输出形式到json

时间:2014-08-17 20:30:05

标签: javascript jquery json

我的表格如下:

<form>
    <div id="studentlist">
        <div class="studentRow">
            <input name="first" type="text" placeholder="First Name">
            <input name="last" type="text" placeholder="Last Name">
        </div>
        <div class="studentRow">
            <input name="first" type="text" placeholder="First Name">
            <input name="last" type="text" placeholder="Last Name">
        </div>
        <div class="studentRow">
            <input name="first" type="text" placeholder="First Name">
            <input name="last" type="text" placeholder="Last Name">
        </div>
    </div>
    <input id="send" value="Submit" type="submit">
</form>

我想以一种格式获得json:

 {"students":[
    {"first":"John", "last":"Doe"}, 
    {"first":"Anna", "last":"Smith"},
    {"first":"Peter", "last":"Jones"},
]}

我尝试使用jquery.serializeJSON并将其称为:

 $('#form').submit(function() {
        console.log( $('#form').serializeJSON() ) ;
        return false;
    });

但我得到的是:

Object { first: "Peter", last: "Jones" }

任何提示如何配置此插件?

提前致谢!

4 个答案:

答案 0 :(得分:1)

这将是我个人的解决方案,但我认为使用PHP更容易做到这一点......

首先,正确格式化HTML:

<form>
    <div id="studentlist">
        <div class="studentRow">
            <input name="students[0][first]" type="text" placeholder="First Name">
            <input name="students[0][last]" type="text" placeholder="Last Name">
        </div>
        <div class="studentRow">
            <input name="students[1][first]" type="text" placeholder="First Name">
            <input name="students[1][last]" type="text" placeholder="Last Name">
        </div>
        <div class="studentRow">
            <input name="students[2][first]" type="text" placeholder="First Name">
            <input name="students[2][last]" type="text" placeholder="Last Name">
        </div>
    </div>
    <input id="send" value="Submit" type="submit">
</form>

然后这将是我的Javascript以获取您正在寻找的数组格式:

var x = $("#studentlist").find('input:last').attr('name').match(/^students\[([\d]+)\]/)[1];
var ary = [];
var obj = {};
for(var i = 0; i<=x; i++){
ary.push({first: $("input[name='students["+i+"][first]']").val(), last: $("input[name='students["+i+"][last]']").val()});
}
obj = { students: ary };
console.log(JSON.stringify(obj));

答案 1 :(得分:1)

由于您已经在使用jquery,因此这可能是解决方案之一:

HTML:

<form id="form">
  <div id="studentlist">
      <div class="studentRow">
          <input name="first" type="text" placeholder="First Name" value="firstname1">
          <input name="last" type="text" placeholder="Last Name" value="lastname1">
      </div>
      <div class="studentRow">
          <input name="first" type="text" placeholder="First Name" value="firstname2">
          <input name="last" type="text" placeholder="Last Name" value="lastname1">
      </div>
      <div class="studentRow">
          <input name="first" type="text" placeholder="First Name" value="firstname3">
          <input name="last" type="text" placeholder="Last Name" value="lastname1">
      </div>
  </div>
  <input value="Submit" type="submit">
</form>

和jquery:

<script type="text/javascript">
jQuery(document).ready(function( $ ) 
{
  $('#form').submit(function(event) 
  {
    var students = [];
    var studentsObject = {};
    event.preventDefault();
    $('.studentRow').each(function()
    {
      students.push
      (
        { 
          first:$(this).find("input[name='first']").val(),
          last: $(this).find("input[name='last']").val()
        }
      );
    });
    studentsObject = {"students":students};
    console.log(JSON.stringify(studentsObject));
  });
});
</script>

答案 2 :(得分:1)

我还没有使用您引用的插件,但这里的解决方案类似于已发布的解决方案。我的目标是使代码更容易理解,因此我将不同的任务分离到自己的函数中。

// Call this function with $('form'), and it will return the desired JSON
function getStudentsJson($form){
    var students = {
        "students": getStudents($form)
    };
    return JSON.stringify(students);
}

function getStudents($form){
    // Extract a list of student objects from the form
    // Each student object has the form {first, last}
    var students = [];
    $form.find(".studentRow").each(function(){
        students.push(getStudent(this));
    });
    return students;
}

function getStudent(row){
    // Extract the student object from a row, in the form {first, last}
    return { 'first': getFirstName(row), 'last': getLastName(row) };
}

function getFirstName(row){
    // Extract the input "first" from the row
    return $(row).find("input[name=first]").val();
}

function getLastName(row){
    // Extract the input "last" from the row
    return $(row).find("input[name=last]").val();
}

答案 3 :(得分:0)

这是一段简单的代码,可以创建所需的json。

var studentsArray = $('.studentRow').map(function(){
    var data = $(':input', this).serializeArray();
    var obj = {};
    obj[data[0].name] = data[0].value;
    obj[data[1].name] = data[1].value;
    return obj;
}).get();
var students = {students: studentsArray};
var json = JSON.stringify(students);