[英]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? 我如何编写代码以读取teamid和teamname以便将它们存储在单独的变量中?
Please Help! 请帮忙!
If it is a JSON string, parse it... 如果它是JSON字符串,请对其进行解析...
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. TeamList
是一个数组,因此,如果您有多个“团队”,则需要遍历它们。
You have an object containing an array TeamList
, which has one object as its elements: 您有一个包含数组
TeamList
的对象,该数组具有一个对象作为其元素:
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... 如果您发布的示例包含为字符串,则可以使用javascript进行解析...
var jsonObject = JSON.parse(myJsonString);
you can then access your array like so... 然后您可以像这样访问数组...
jsonObject.TeamList
and each item in TeamList... 以及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... 最后假设您在TeamList中有一项,并尝试直接回答您的问题...
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:
基本上,使用json解析后,您将对结果执行以下操作:
result["TeamList"][0]["teamname"]
to get teamname and result["TeamList"][0]["teamid"]
to get teamid. result["TeamList"][0]["teamname"]
获取组名, result["TeamList"][0]["teamid"]
获取组名。
If you can use json_decode, like this : 如果可以使用json_decode,如下所示:
$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? 您已将问题标记为jQuery? We're you wanting to display this information on a page?
您要在页面上显示此信息吗?
Given some sample html: 给定一些示例html:
<label>Team ID:</label>
<div id="teamid"></div>
<label>Team Name:</label>
<div id="teamname"></div>
And a little jquery: 还有一点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.
正如其他人指出的那样,如果有多个团队,则需要遍历整个集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.