我有一个看起来像这样的Json文件
"timeline": [
{
"t0": [
{ "x": 0.000000, "y": 0.000000, "z": 0.000000 },
{ "x": -0.120473, "y": 4.998491, "z": 0.000000 },
{ "x": -0.323933, "y": 9.994292, "z": 0.000000 },
{ "x": -0.610325, "y": 14.986026, "z": 0.000000 },
{ "x": -0.979571, "y": 19.972315, "z": 0.000000 }, {....}
以此类推。
因此,存在一个对象“时间轴”,该对象由61个称为“ t0”,“ t1”,...“ t60”的对象组成,并且每个对象都是一个数组,其点由x-,y-和z坐标。
那么有人可以告诉我如何访问t0对象,甚至更好地访问其中的单独坐标吗?
json文件是否通常是这种方式?
最好的问候
亚历克斯
答案 0 :(得分:1)
data = {"timeline": [{"t0": [{ "x": 0.000000, "y": 0.000000, "z": 0.000000 },{ "x": -0.120473, "y": 4.998491, "z": 0.000000 },{ "x": -0.323933, "y": 9.994292, "z": 0.000000 },{ "x": -0.610325, "y": 14.986026, "z": 0.000000 },{ "x": -0.979571, "y": 19.972315, "z": 0.000000 }]},{"t1": [{ "x": 0.000000, "y": 0.000000, "z": 0.000000 },{ "x": -0.120473, "y": 4.998491, "z": 0.000000 },{ "x": -0.323933, "y": 9.994292, "z": 0.000000 },{ "x": -0.610325, "y": 14.986026, "z": 0.000000 },{ "x": -0.979571, "y": 19.972315, "z": 0.000000}] }]}
变量数据包含示例json对象。
let cnt = 0;
for(let obj of data.timeline){
var str= "t"+cnt;
for(let p of obj[str]){
console.log("x is :"+p.x);
console.log("y is :"+p.y);
console.log("z is :"+p.z);
}
cnt=cnt+1;
}
使用此方法,您可以从json数据中提取此类json对象的单独坐标。如果您使用不同类型的json数据,则代码将被更改。
答案 1 :(得分:0)
在这里简单地编写您的逻辑
var data = {"timeline": [{"t0": [
{ "x": 0.000000, "y": 0.000000, "z": 0.000000 },
{ "x": -0.120473, "y": 4.998491, "z": 0.000000 },
{ "x": -0.323933, "y": 9.994292, "z": 0.000000 },
{ "x": -0.610325, "y": 14.986026, "z": 0.000000 },
{ "x": -0.979571, "y": 19.972315, "z": 0.000000 }
]}]}
console.log(data.timeline[0]["t0"]);
或者您可以尝试
$.each(data.timeline, function(key, val) {console.log(val)})
答案 2 :(得分:0)
代码注释,显示每件事。无需单独的计数器。
let obj = {
"timeline": [{
"t0": [{
"x": 0.000000,
"y": 0.000000,
"z": 0.000000
},
{
"x": -0.120473,
"y": 4.998491,
"z": 0.000000
},
{
"x": -0.323933,
"y": 9.994292,
"z": 0.000000
},
{
"x": -0.610325,
"y": 14.986026,
"z": 0.000000
}
]
},
{
"t1": [{
"x": 0.000000,
"y": 0.000000,
"z": 0.000000
},
{
"x": -0.120473,
"y": 4.998491,
"z": 0.000000
},
{
"x": -0.323933,
"y": 9.994292,
"z": 0.000000
},
{
"x": -0.610325,
"y": 14.986026,
"z": 0.000000
}
]
},
{
"t2": [{
"x": 0.000000,
"y": 0.000000,
"z": 0.000000
},
{
"x": -0.120473,
"y": 4.998491,
"z": 0.000000
},
{
"x": -0.323933,
"y": 9.994292,
"z": 0.000000
},
{
"x": -0.610325,
"y": 14.986026,
"z": 0.000000
}
]
}
]
};
//two different ways to access
let onepoint = obj["timeline"][1]["t1"][2]["x"]
console.log(onepoint);
let onepointDirect = obj.timeline[1].t1[2].x
console.log(onepointDirect);
// timeline array process
for (let i = 0; i < obj.timeline.length; i++) {
// objects inside each array
for (let tobj in obj.timeline[i]) {
console.log("tobj", tobj); //t0,t1 etc.
// array of objects (the x,y,z things
for (let t = 0; t < obj.timeline[i][tobj].length; t++) {
console.log(tobj, t, obj.timeline[i][tobj][t]);
// each x
console.log("x:", obj.timeline[i][tobj][t].x);
}
}
}