我试图在Node js中创建一个JSON对象,但没有任何成功.例如,创建一个像这样的对象:
{ 'Orientation Sensor': [ { sampleTime: '1450632410296', data: '76.36731:3.4651554:0.5665419' }, { sampleTime: '1450632410296', data: '78.15431:0.5247617:-0.20050584' } ], 'Screen Orientation Sensor': [ { sampleTime: '1450632410296', data: '255.0:-1.0:0.0' } ], 'MPU6500 Gyroscope sensor UnCalibrated': [ { sampleTime: '1450632410296', data: '-0.05006743:-0.013848438:-0.0063915867}, { sampleTime: '1450632410296', data: '-0.051132694:-0.0127831735:-0.003325345'}]}
但是以一种动态的方式,不知道每个项目的大小.Node js有类似的东西吗?非常感谢你
我相信你正在寻找的是一种使用数组作为对象值的方法:
var o = {} // empty Object var key = 'Orientation Sensor'; o[key] = []; // empty Array, which you can push() values into var data = { sampleTime: '1450632410296', data: '76.36731:3.4651554:0.5665419' }; var data2 = { sampleTime: '1450632410296', data: '78.15431:0.5247617:-0.20050584' }; o[key].push(data); o[key].push(data2);
这是标准的JavaScript,而不是NodeJS特有的.为了将其序列化为JSON字符串,您可以使用本机JSON.stringify
:
JSON.stringify(o); //> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'
JavaScript Object()
构造函数创建一个可以为其分配成员的Object.
myObj = new Object() myObj.key = value; myObj[key2] = value2; // Alternative