[英]How do I access the objects from json to automate dropdown
I have been trying for a while now to access the contents of a json object. 我已经尝试了一段时间,以访问json对象的内容。 I am using jQuery to try and automate a dropdown.
我正在使用jQuery来尝试使下拉列表自动化。
Here is the json code 这是JSON代码
{
"Kingston":
{
"tots": [
"9.15-10.00am"
],
"kickers": [
"9.15-10.00am"
],
"strikers": [
"9.15-10.00am"
],
"academy": [
"9.15-10.00am"
]
}
,
"Knaphill":
{
"tots": [
"9.15-10.00am"
],
"kickers": [
"9.15-10.00am"
],
"strikers": [
"9.15-10.00am"
],
"academy": [
"9.15-10.00am"
]
}
}
Here is what I have so far for the javascript. 到目前为止,这是我对javascript的了解。 It keeps giving me an undefined error.
它一直给我一个不确定的错误。
jQuery( document ).ready(function() {
console.log("ready");
$.getJSON("sessions.json", function(data) {
var key = <?php echo json_encode($form->data['hb_venue']); ?>;
var cat = "tots";
var c = [];
switch (key) {
case "Kingston":
c = data.Kingston.cat.split(",");
break;
default:
c = '<option>Choose a class</option>';
}
var $sessList = $("#cb_sessions");
$sessList.empty();
$.each(c, function(index, value) {
$sessList("<option>" + value + "</option>");
});
});
});
You have to realise that JSON works as an array (or objects) of objects. 您必须认识到JSON可以作为对象的数组(或对象)。
The reason you are getting an undefined error is because u are accessing your object wrongly. 出现未定义错误的原因是因为u错误地访问了对象。
This code c = data.Kingston.cat.split(",");
这段代码
c = data.Kingston.cat.split(",");
is wrong because it is equivalent to doing this: 是错误的,因为它等效于执行以下操作:
c = data.Kingston."tots".split(",");
That is the wrong way to access the object. 那是访问对象的错误方法。 This is the correct way:
这是正确的方法:
c = data["Kingston"][cat][0].split(",");
EDIT: the reason for the extra [0]
is because data["Kingston"][cat]
returns an object, so to access the string in the object, you have to access it by data["Kingston"][cat]
编辑:额外
[0]
的原因是因为data["Kingston"][cat]
返回一个对象,因此要访问对象中的字符串,必须通过data["Kingston"][cat]
访问它
To get your values, you should probably do something like this: 为了获得您的价值观,您可能应该做这样的事情:
data.Kingston.tots
data.Kingston.kickers
data.Kingston.strikers
data.Kingston.academy
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.