0

I have this string that I get from an outside data source. It looks like this:

var myString =  "Worker Management System :

    Your request has been submitted
    ________________________________________
    Your Account User Info: 
    Name : Doe, John, A 
    ID : JDOE123    
    Email :         
    Title : Worker
    BusinessUnit : BARN
    Department : PIGS   
    EmployeeID :            
    SupervisorName : Doe, Jane, B
    HireDate : 02/22/2002   
    Role : Feed Pigs;   
    ManagerEmail : JaneDoe@mail.com

    City : New York
    State : NY
    ZipCode : 12345
    Phone : --  
    "

I'd like to parse this into a JSON (or something that i can work with) so that I can call maybe myString.Name and have it return Doe, John, A.

Is this possible? It's not an option for my to modify the way I get this string, I'm just trying to format it so I can easily extract the data from it.

I've looked into Douglas Crockford's JSON.parse, but that doesn't do me any good if my string isn't already properly formatted.

Jeff
  • 1,800
  • 8
  • 30
  • 54
  • 2
    Firstly, you have to convert your string to object. It can be done with text parsing. JSON has nothing to do here. – VisioN Jan 22 '13 at 23:29
  • 2
    That isn't even valid JavaScript. Is the `var myString =` part from the outside source? – PleaseStand Jan 22 '13 at 23:30

1 Answers1

2
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};


function my_string_to_object(myString)
{
    var tmp = myString.split('Your Account User Info: ',2);
    var tmp = tmp[1].split("\n");    
    var obj = {};
    for(var k=0;k<tmp.length;k++) {    
        var line = tmp[k].split(' : ');
        if(typeof(line[1]) != 'undefined') {
            obj[ line[0].trim() ] = line[1].trim();
        }
    }
    return obj;
}
Peter
  • 16,453
  • 8
  • 51
  • 77