如何解析对象并为RECORD后的每个Sensor生成嵌套对象?
实现方案
可以通过遍历对象字段、筛选目标传感器键的方式完成结构转换,以下是两种常用编程语言的实现示例:
JavaScript 实现
输入数据
const input = { "TIMESTAMP": "2022-10-21 13:55:00", "RECORD": "0", "Sensor1": "1.654", "Sensor2": "1.176", "Sensor3": "0.706" };
转换逻辑
const output = {}; const timestamp = input.TIMESTAMP; // 遍历所有字段,筛选以"Sensor"开头的键 Object.keys(input).forEach(key => { if (key.startsWith('Sensor')) { output[key] = { TIMESTAMP: timestamp, Value: input[key] }; } }); console.log(output);
输出结果
{ "Sensor1": { "TIMESTAMP": "2022-10-21 13:55:00", "Value": "1.654" }, "Sensor2": { "TIMESTAMP": "2022-10-21 13:55:00", "Value": "1.176" }, "Sensor3": { "TIMESTAMP": "2022-10-21 13:55:00", "Value": "0.706" } }
Python 实现
输入数据
input_data = { "TIMESTAMP": "2022-10-21 13:55:00", "RECORD": "0", "Sensor1": "1.654", "Sensor2": "1.176", "Sensor3": "0.706" }
转换逻辑
output = {} timestamp = input_data["TIMESTAMP"] for key, value in input_data.items(): if key.startswith("Sensor"): output[key] = { "TIMESTAMP": timestamp, "Value": value } print(output)
内容的提问来源于stack exchange,提问作者JohnnyPicnic
相关产品推荐
相关产品推荐

