www.webdeveloper.com
Results 1 to 6 of 6

Thread: Text to json format question

  1. #1
    Join Date
    Dec 2005
    Location
    TX
    Posts
    7,943

    Question Text to json format question

    If I have an external file containing this kind of information:
    Code:
      var Employees = [               // text file contents
          "Lname,Fname,Age,Sex,Ext",      // description line
          "Alley,Gasoline,75,M,x1234",
          "Boop,Betty,24,F,x2345",
          "Cow,Clarabel,35,F,x3456",
          "Duck,Daffy,58,M,x4567",
          "Fudd,Elmer,64,M,x5678"
      ];
    I would like to transform this using JS into a json object with a format like this:
    Code:
      var jsonObj["Lname,Fname"] = {'Age':'???', 'Sex':'???', 'Ext':'???' }
    How would I set the 'Age', 'Sex' and 'Ext' information for each employee?
    (This assumes I am creating the jsonObj correctly [???])

    Or should the transform be something like this?
    Code:
      jsonObject = {'Names':'', {'Age':'', 'Sex':'', 'Ext':'' } }
      jsonObj = new jsonObject;
    
    // followed by some assignment to each field like
    // jsonObj{Names.Emp[0]+','+Emp[1], {
    //            'Age':Emp[2],'Sex':Emp[3],'Ext':Emp[4] } }
    // after each 'Employee' element has been split to an array 'Emp'
    This json stuff intrigues me, but I'm having a tough time wrapping my head around it.


    Am I going in the right direction?
    Is this possible using JS without retyping my initial database?

  2. #2
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    Code:
      var Employees = [               // text file contents
          "Lname,Fname,Age,Sex,Ext",      // description line
          "Alley,Gasoline,75,M,x1234",
          "Boop,Betty,24,F,x2345",
          "Cow,Clarabel,35,F,x3456",
          "Duck,Daffy,58,M,x4567",
          "Fudd,Elmer,64,M,x5678"
      ];
    
    var output={}; //the final object to hold employees by key
    var cols=Employees[0].split(","); //gets col names
      cols[0]+=","+cols[1]; //merges last and first name columns
      cols.splice(1,1); //kills now-redundant Fname column
    
    Employees.slice(1). //skips col headers
      map(function(row, index){ //iterates array via [].map()
        var cells=row.split(","); //grabs row's cols
        cells[0]+=","+cells[1]; //merges last and first name columns
        cells.splice(1,1); //kills now-redundant Fname column
        var sub=output[cells[0]]={}; //empty result "row"
        cells.slice(1).map(function(cell, colIndex){//iterates cells using [].map()
            //strongly sets the rowObject's column's value using the current cell:
            sub[ cols[ colIndex +1 ] ] = isFinite(cell) ? cell*1 : cell; 
        });//end cell map()
    });;//end row map()
    
    
    alert(
        JSON.stringify(  
            output , null, "\t"
        )
    );
    Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com

  3. #3
    Join Date
    Dec 2005
    Location
    TX
    Posts
    7,943

    Thumbs up Thank you!

    Thank you. I'll study on this a while, but at least it's looking manageable!

  4. #4
    Join Date
    Dec 2005
    Location
    TX
    Posts
    7,943

    Question Another look please ...

    He's baaack!!!

    In trying to understand the code you posted, I made 2 modifications.
    1. I displayed an alert of the 'output' keys ... seems to work fine

    2. I tried to display the part of the 'output' using output{keys}.Age ... No Go!

    I'm sure it's something I don't understand, but could you look at my code and see what I am still misunderstanding?
    I highlighted the changes in RED.

    If you uncomment the last of the testKeys function /* */ it breaks.
    With that section commented out, it works as I expect.

    Code:
    <html>
    <head>
    <title>Array to JSON</title>
    
    <script type="text/javascript">
      var Employees = [               	// text file contents
          "Lname,Fname,Age,Sex,Ext",    // description line
          "Alley,Gasoline,75,M,x1234",
          "Boop,Betty,24,F,x2345",
          "Cow,Clarabel,35,F,x3456",
          "Duck,Daffy,58,M,x4567",
          "Fudd,Elmer,64,M,x5678"
      ];
    
      var output={}; //the final object to hold employees by key
      
      var cols=Employees[0].split(","); //gets col names
      cols[0]+=","+cols[1]; 			//merges last and first name columns
      cols.splice(1,1); 				//kills now-redundant Fname column
    
      Employees.slice(1). 				//skips col headers
      map(function(row, index){ 		//iterates array via [].map()
        var cells=row.split(","); 		//grabs row's cols
        cells[0]+=","+cells[1]; 		//merges last and first name columns
        cells.splice(1,1); 				//kills now-redundant Fname column
        var sub=output[cells[0]]={}; 	//empty result "row"
    
        cells.slice(1).map(function(cell, colIndex){	//iterates cells using [].map()
            //strongly sets the rowObject's column's value using the current cell:
            sub[ cols[ colIndex +1 ] ] = isFinite(cell) ? cell*1 : cell; 
        });//end cell map()
    
      });;//end row map()
    
      alert( JSON.stringify( output , null, "\t" ) );
    
      function testKeys() {
        var str = 'Keys\n';  for (var i in output) { str += i+'\n'; }
        alert(str);
    
        str = 'Recs\n';
    /*
        for (var i in output) {
          str += i+'\t'+output{i}.Age;   // +'\t'+output{i}.Sex+'\t'+output{i}.Ext;
        }
    */
        alert(str);
      }
    
    </script>
    
    </head>
    <body>
    <button onclick="testKeys()">Keys & Recs</button>
    </body>
    </html>

  5. #5
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    Code:
      var Employees = [               	// text file contents
          "Lname,Fname,Age,Sex,Ext",    // description line
          "Alley,Gasoline,75,M,x1234",
          "Boop,Betty,24,F,x2345",
          "Cow,Clarabel,35,F,x3456",
          "Duck,Daffy,58,M,x4567",
          "Fudd,Elmer,64,M,x5678"
      ];
    
      var output={}; //the final object to hold employees by key
      
      var cols=Employees[0].split(","); //gets col names
      cols[0]+=","+cols[1]; 			//merges last and first name columns
      cols.splice(1,1); 				//kills now-redundant Fname column
    
      Employees.slice(1). 				//skips col headers
      map(function(row, index){ 		//iterates array via [].map()
        var cells=row.split(","); 		//grabs row's cols
        cells[0]+=","+cells[1]; 		//merges last and first name columns
        cells.splice(1,1); 				//kills now-redundant Fname column
        var sub=output[cells[0]]={}; 	//empty result "row"
    
        cells.slice(1).map(function(cell, colIndex){	//iterates cells using [].map()
            //strongly sets the rowObject's column's value using the current cell:
            sub[ cols[ colIndex +1 ] ] = isFinite(cell) ? cell*1 : cell; 
        });//end cell map()
    
      });;//end row map()
    
     // alert( JSON.stringify( output , null, "\t" ) );
    
      function testKeys() {
        var str = 'Keys\n';  for (var i in output) { str += i+'\n'; }
        alert(str);
    
        str = 'Recs\n';
    
        for (var i in output) {
          str += i+'\t'+output[i].Age+'\t'+output[i].Sex+'\t'+output[i].Ext+'\n';
        }
    
        alert(str);
      }
    
    testKeys()
    Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com

  6. #6
    Join Date
    Dec 2005
    Location
    TX
    Posts
    7,943

    Thumbs up

    I see the { error } of my [ ways ] !

    Thank you again!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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

"

"

X vBulletin 4.2.2 Debug Information

  • Page Generation 0.14269 seconds
  • Memory Usage 2,898KB
  • Queries Executed 15 (?)
More Information
Template Usage (33):
  • (1)SHOWTHREAD
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (1)ad_thread_first_post_content
  • (1)ad_thread_last_post_content
  • (6)bbcode_code
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (6)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (6)postbit
  • (6)postbit_onlinestatus
  • (6)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (26):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (70):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates