anujit
anujit

Reputation: 99

How to access a text file using javascript?

I am making a jquery ajax call to the following text file:

sport=Table Tennis&groups=no&no_groups=&grp_names=&teams=1^China^6157~2^Finland^6158~3^Sweden^6159~4^Japan^6149~5^Korea^6154&Endstr=End

The call is working fine. But I really don't know how to access a particular value like lets say, 'China' from the above text file? I am trying tis for the first time. please help..

Upvotes: 0

Views: 140

Answers (3)

closure
closure

Reputation: 7452

Here is code to parse your data. It would have been straight forward if you have chosen JSON as return data.

function myParser() {

    var str = "sport=Table Tennis&groups=no&no_groups=&grp_names=&teams=1^China^6157~2^Finland^6158~3^Sweden^6159~4^Japan^6149~5^Korea^6154&Endstr=End";
    var arPairs = str.split("&");
    var outObj = {};
    for (var i=0; i < arPairs.length; i++) {
      var arTemp = arPairs[i].split("=");
      var key = arTemp[0];
      var value = arTemp[1];
      if (key === "teams") {
        arTemp = value.split("~");
        var teamObj = {};
        for (var j=0; j < arTemp.length; j++) {
          var arTeamData = arTemp[j].split("^");
          teamObj[arTeamData[1]] = arTeamData[2];
        }
        value = teamObj;
      }
      outObj[key] = value;
    }
    return outObj;
}

output: Is an array having all your data available. You can refer it as:

var outObj = myParser(); console.log(outObj.sport); // Prints "Table Tennis" console.log(outObj.teams.china) // Prints china data

Upvotes: 0

hyankov
hyankov

Reputation: 4130

Don't use such file structure. Use JSON instead. i.e:

{
   "sport":"Table Tennis",
   "groups":false,
   "no_groups":"",
   "grp_names":[

   ],
   "teams":[
      {
         "China":6157
      },
      {
         "Finland":6158
      },
      {
         "Sweden":6159
      },
      {
         "Japan":6149
      },
      {
         "Korea":6154
      }
   ],
   "Endstr":"End"
}

Then, after you parse it with $.get or $.ajax, you just access:

data.sports

for example.

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337713

Here is the parseParams plugin which you can use to split a querystring into an array.

You can use it like this:

var querystring = 'sport=Table Tennis&groups=no&no_groups=&grp_names=&teams=1^China^6157~2^Finland^6158~3^Sweden^6159~4^Japan^6149~5^Korea^6154&Endstr=End';
var paramsObj = $.parseParams(querystring);
alert(paramsObj.sport); // = Table Tennis

Upvotes: 1

Related Questions