这是形成服务器期望的JSON的代码。但是存在一些问题
<!DOCTYPE html>
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//var acc = {};
var x = 10;
var y = 20;
var z = 30;
var output = [];
output[0] = {
name: "Accelerometer_X",
value: JSON.parse(x), // retrieve x
};
output[1] = {
name: "Accelerometer_Y",
value: JSON.parse(y), // retrieve y
};
output[2] = {
name: "Accelerometer_Z",
value: JSON.parse(z) // retrieve z
};
var record = [];
record[0] = {
starttime: new Date(),
output: output,
};
var observations = [];
observations[0] = {
sensor: "",
record: record,
};
var fromData = {};
fromData.version = "1.0.1";
fromData.observations = observations;
alert(JSON.stringify(fromData));
console.log(JSON.stringify(fromData));
//-->
</script>
</body>
</html>
输出JSON是:
{
"version": "1.0.1",
"observations": [
{
"sensor": "",
"record": [
{
"starttime": "2014-08-15T16:01:34.711Z",
"output": [
{
"name": "Accelerometer_X",
"value": 10
},
{
"name": "Accelerometer_Y",
"value": 20
},
{
"name": "Accelerometer_Z",
"value": 30
}
]
}
]
}
]
}
但是预期的JSON是:
{
"version": "1.0.1",
"observations": [
{
"sensor": "",
"record": [
{
"starttime": "1-JAN-2014 15:30:00 IST",
"output": [
{
"name": "Accelerometer_X",
"value": "10"
},
{
"name": "Accelerometer_Y",
"value": "20"
},
{
"name": "Accelerometer_Z",
"value": "30"
}
]
}
]
}
]
}
预期JSON中的值在&#34;&#34;即
{
"name": "Accelerometer_Z",
"value": "30"
}
但是制作的JSON是:
{
"name": "Accelerometer_Z",
"value": 30
}
另一个问题是启动时间。预期的启动时间格式为
1-JAN-2014 15:30:00 IST
产生的开始时间是:
2014-08-15T16:01:34.711Z
我不知道如何改变这一点。请帮帮我。
答案 0 :(得分:0)
您不应对要放在对象中的值使用JSON.parse
。 JSON.parse
方法用于将JSON字符串解析为对象,但值不是JSON字符串。
删除JSON.parse
调用(因为它不会更改值),并使用toString
方法将值转换为字符串:
output[0] = {
name: "Accelerometer_X",
value: x.toString(),
};
output[1] = {
name: "Accelerometer_Y",
value: y.toString(),
};
output[2] = {
name: "Accelerometer_Z",
value: z.toString()
};
没有用于格式化日期的功能构建,您需要自己创建。类似的东西:
function formatDate(d) {
return d.getDate() + '-' + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + " IST";
}
用法:
record[0] = {
starttime: formatDate(new Date()),
output: output,
};
答案 1 :(得分:0)
这是迄今为止的代码:
<!DOCTYPE html>
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//var acc = {};
var x = 10;
var y = 20;
var z = 30;
//var accString = JSON.stringify(acc); // that's what you have
var output = [];
output[0] = {
name: "Accelerometer_X",
value: x.toString(), // retrieve x
};
output[1] = {
name: "Accelerometer_Y",
value: y.toString(), // retrieve y
};
output[2] = {
name: "Accelerometer_Z",
value: z.toString() // retrieve z
};
var record = [];
record[0] = {
starttime: new Date(),
output: output,
};
var observations = [];
observations[0] = {
sensor: "",
record: record,
};
var fromData = {};
fromData.version = "1.0.1";
fromData.observations = observations;
alert(JSON.stringify(fromData));
console.log(JSON.stringify(fromData));
//-->
</script>
</body>
</html>
但现在时间仍然存在问题。有人解决这个问题吗?