gpt4 book ai didi

javascript - 如何通过 javaScript 从 json 访问数据?

转载 作者:搜寻专家 更新时间:2023-10-30 22:24:49 26 4
gpt4 key购买 nike

我正在尝试使用 JS 进行数据可视化,从动态 json 文件获取值,但我无法通过控制台可视化我的数据。

想法是能够使用这 4 个值(outputValue0、outputValue1、outputValue2、outputValue3)来修改形状和自身的颜色。我应该如何调用我的变量以在 javaScript 中访问它们?

这是我的代码:

var lines = "waiting for data"; 
var val0 = 0; // I get a 0, of course, but I need the actual value
var val0 = []; //I get nothing with this

function setup() {
createCanvas(400,400);
loadJSON('http://www.----------.com/data_to_json.php', gotData);
}

Object.size = function(obj){
var size = 0, key;
for(key in obj){
if(obj.hasOwnProperty(key)) size++;
}
return size;
}

function gotData(data) {

var size = Object.size(data) - 1;
console.log(size);
console.log(data[size]['timeStamp']);
console.log(data[size]['outputValue0'] + " " + data[size]['outputValue1'] + " " + data[size]['outputValue2']+ " " + data[size]['outputValue3']);
lines = size;
var val0 = data[size]['outputValue0'];

}

function draw(){
background(158, 152, 207);
textAlign(LEFT);
fill(0);
text('Emotional analysis', 10, height - 370);
text(lines + ' emotions stored',10,height -20);
text(val0,10,height -60)

}

我的控制台上有一些错误,但我认为这不相关:

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable El uso del sensor de orientación está obsoleto. (the use of the sensor is obsolete) p5.js:9298:6 El uso del sensor de moviento está obsoleto. (the use of the sensor is obsolete) p5.js:9298:6 240 sketch.js:20:3 2019-02-08 22:03:09 sketch.js:21:3 20 20 19 20 sketch.js:22:3

json 文件如下所示:

[{"timeStamp":"2019-02-08 13:38:53","outputValue0":"18","outputValue1":"18","outputValue2":"18","outputValue3":"18"},
{"timeStamp":"2019-02-08 13:39:03","outputValue0":"18","outputValue1":"18","outputValue2":"19","outputValue3":"18"},
{"timeStamp":"2019-02-08 13:39:13","outputValue0":"18","outputValue1":"18","outputValue2":"19","outputValue3":"18"},
{"timeStamp":"2019-02-08 13:39:23","outputValue0":"18","outputValue1":"19","outputValue2":"19","outputValue3":"19"},
{"timeStamp":"2019-02-08 13:39:33","outputValue0":"18","outputValue1":"19","outputValue2":"20","outputValue3":"19"}]

最佳答案

您似乎试图填充一些全局变量。但是你在范围上犯了错误,而且这通常被认为是有缺陷的设计模式。此外,目前您似乎没有实际调用 draw() 函数的地方。

如果 draw() 接受一些参数,例如

function draw(val0, val1, val2, val3) {

然后在 gotData 函数中你可以写

draw(data[size]['outputValue0'], data[size]['outputValue1'], data[size]['outputValue2'], data[size]['outputValue3']); 

将值传递给它,并改变你的形状。

关于javascript - 如何通过 javaScript 从 json 访问数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54600610/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com