简体   繁体   中英

Read Json Variable

{"TeamList" : [{"teamid" : "2","teamname" : "Milan"}]}

How do i write the code to read the teamid and teamname so as to store them in seperate variables?

Please Help!

If it is a JSON string, parse it...

var obj = jQuery.parseJSON(jsonString);

Then work with the information

obj.TeamList[0].teamid;
obj.TeamList[0].teamname;

TeamList is an array so if you have more than one "team" you'll need to loop over them.

You have an object containing an array TeamList , which has one object as its elements:

var tl = {"TeamList" : [{"teamid" : "2","teamname" : "Milan"}]};

var id = tl.TeamList[0].teamid;
var name = tl.TeamList[0].teamname;

If the example you have posted in contained as a string you can parse it like so with javascript...

var jsonObject = JSON.parse(myJsonString);

you can then access your array like so...

jsonObject.TeamList

and each item in TeamList...

jsonObject.TeamList[i].teamid
jsonObject.TeamList[i].teamname

finally assuming you have one item in TeamList and making an attemp to directly answers you question...

var teamid = jsonObject.TeamList[0].teamid;
var teamname = jsonObject.TeamList[0].teamname;

hope that makes sense

in which language? Basically after parsing using json you would do something like this on the result:

result["TeamList"][0]["teamname"] to get teamname and result["TeamList"][0]["teamid"] to get teamid.

If you can use json_decode, like this :

$content = '{"TeamList" : [{"teamid" : "2","teamname" : "Milan"}]}';
$json = json_decode($content);
$obj = $json->{'TeamList'}[0];
print $obj->{'teamid'}."//".$obj->{'teamname'};

You had tagged your question as jQuery? We're you wanting to display this information on a page?

Given some sample html:

<label>Team ID:</label>
<div id="teamid"></div>

<label>Team Name:</label>
<div id="teamname"></div>

And a little jquery:

var obj = {"TeamList" : [{"teamid" : "2","teamname" : "Milan"}]};

$('#teamid').html(obj.TeamList[0].teamid);
$('#teamname').html(obj.TeamList[0].teamname);

Would allow you to accomplish this. As others have pointed out you would need to iterate over the collection if there were multiple teams.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM