Javascript 如何生成json子节点(json中的json)?

Javascript 如何生成json子节点(json中的json)?,javascript,jquery,asp.net-mvc,json,Javascript,Jquery,Asp.net Mvc,Json,我尝试使用jquery+json获取表单中的所有元素,并构建一个json变量,以在ASP.NETMVC方法中发布 $.fn.serializeObject = function () { var o = {}; var a = this.serializeArray(); $.each(a, function () { if (o[this.name]) { if (!o[this.name].push) { o[this.name] = [o[this.n

我尝试使用jquery+json获取表单中的所有元素,并构建一个json变量,以在ASP.NETMVC方法中发布

 $.fn.serializeObject = function () {
  var o = {};
  var a = this.serializeArray();
  $.each(a, function () {
   if (o[this.name]) {
    if (!o[this.name].push) {
     o[this.name] = [o[this.name]];
    }
    o[this.name].push(this.value || '');
   } else {
    o[this.name] = this.value || '';
   }
  });
  return o;
 };


 $("#btnPost").click(function () {
     alert(JSON.stringify($("#frm").serializeObject())));
 }); 
它方法获取表单中的所有字段并构建JSON,但它不会将JSON放在JSON中

例如:

如果我有以下表格:

<input name="person.name"><input name="person.age"><input name="person.address.street">
我需要一个插件或一些函数来生成如下内容:

{ "person": { "name" : "??", "age" : "??", "address":{ "street": "??" } } }
你的问题不是“JSON中的JSON”(这是一个误称——JSON很好地支持嵌套),你的问题是你误解了这个过程的工作原理

您的
serializeObject()
方法只是读取名称-作为字符串,javascript中没有任何东西可以让此过程“自动”为您解析点符号-句点只是作为属性名称的一部分处理

您需要在句点上拆分名称并相应地进行操作。稍微递归一下,你就到了

$.fn.serializeObject = function()
{
  var o = {};
  var a = this.serializeArray();
  $.each( a, function()
  {
    if ( /\./.test( this.name ) )
    {
      resolveProperty( o, this.name.split( '.' ), this.value );                              
    } else {
      o[this.name] = this.value;
    }
  } );
  return o;

  function resolveProperty( object, properties, value )
  { 
    if ( properties.length > 1 )
    {
      var property = properties.shift();

      if ( 'undefined' == typeof object[property] )
      {
        object[property] = {};
      }
      resolveProperty( object[property], properties, value );
    } else {
      object[properties.shift()] = value;
    }
  }
};
$.fn.serializeObject = function()
{
  var o = {};
  var a = this.serializeArray();
  $.each( a, function()
  {
    if ( /\./.test( this.name ) )
    {
      resolveProperty( o, this.name.split( '.' ), this.value );                              
    } else {
      o[this.name] = this.value;
    }
  } );
  return o;

  function resolveProperty( object, properties, value )
  { 
    if ( properties.length > 1 )
    {
      var property = properties.shift();

      if ( 'undefined' == typeof object[property] )
      {
        object[property] = {};
      }
      resolveProperty( object[property], properties, value );
    } else {
      object[properties.shift()] = value;
    }
  }
};