www.webdeveloper.com
Results 1 to 6 of 6

Thread: Text to json format question

  1. #1
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,444

    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"
        )
    );

  3. #3
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,444

    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
    FL
    Posts
    7,444

    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()

  6. #6
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,444

    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



Recent Articles