开发者

How i can make json child nodes (JSON inside JSON)?

开发者 https://www.devze.com 2023-01-10 23:14 出处:网络
I try to开发者_运维问答 use the jquery + json to get all elements in form and build a JSON var to post in a ASP.NET MVC method.

I try to开发者_运维问答 use the jquery + json to get all elements in form and build a JSON var to post in a ASP.NET MVC method.

 $.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())));
 }); 

It method get all fields in a form and build a JSON, but it dont put JSON inside JSON.

Example:

If i have the follow form:

<input name="person.name"><input name="person.age"><input name="person.address.street">

The serialized string build a JSON like this

{ "person.name": "??", "person.age": "??", "person.address.street": "??" }

I need a plugin or some function to generate like this:

{ "person": { "name" : "??", "age" : "??", "address":{ "street": "??" } } }


Your problem is not "JSON within JSON" (which is a misnomer anyway - JSON supports nesting just fine), your problem is you've misinterpreted how this process works.

Your serializeObject() method is just reading the names - as strings There's nothing in javascript that makes this process "automagically" resolve the dot-notation for you - the periods are just treated as part of the property name.

You'll need to split the names on the periods and proceed accordingly. A little dab of recursion and you're there.

$.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;
    }
  }
};
0

精彩评论

暂无评论...
验证码 换一张
取 消