SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    16
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    serialize and deserialize complex json

    how to map the JSON to a complex object, for example, an Employee object has a Company field , how to serialize and deserialize json to form field ?

    Thanks

    Code:
    {id:'1234', name:'john', company:{name:'ABC', type:'Retail'}}
    
    <form>
    <input name="id" type="input" /> 
    <input name="name" type="input" /> 
    <input name="company.id" type="input" />
    <input name="company.type" type="input" />
    </form>

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,890
    Mentioned
    211 Post(s)
    Tagged
    12 Thread(s)
    Not sure how much sense this makes, but you could do:

    Code:
    <!DOCTYPE HTML>
    <html>
      <head>
        <meta charset="utf-8">
        <title>My serialize</title>
      </head>
      
      <body>
        <form>
          <input name="id" type="input" /> 
          <input name="name" type="input" /> 
          <input name="company_name" type="input" />
          <input name="company_type" type="input" />
        </form>
    
        <script>
          function mySerialize(json, prependText){
            var keys = Object.keys(json);
    
            for (var i=0; i<keys.length; i++){
              if(typeof json[keys[i]] === 'object'){
                mySerialize(json[keys[i]], 'company_');
              } else {
                field = prependText + keys[i];
                document.forms[0][field].value = json[keys[i]];
              }
            }
          }
    
          var details = {id:'1234', name:'john', company:{name:'ABC', type:'Retail'}};
          mySerialize(details, '');
        </script>
      </body>
    </html>

  3. #3
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Just a quick HTML observation. I'd probably use form fieldsets to keep with the JSON structure.

    Code:
    <form>
      <input name="id" type="input" /> 
      <input name="name" type="input" /> 
      <filedset name="company">
        <input name="id" type="input" />
        <input name="type" type="input" />
      </fieldset>
    </form>


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •