JSON 整理与类型生成可运行案例
传感器读数:递归排序对象字段并保留数组顺序
递归按键名整理对象,便于人工检查。readings 的数组顺序不变;排序后的 JSON 文本不能直接当作通用签名规范或所有语言一致的 canonical JSON。
试一试
在完整工具中打开 ↗示例工作台
JSON 整理与类型生成
pretty键排序运行结果
{
"data": {
"readings": [
{
"alarm": true,
"calibration": {
"points": [
0,
100
],
"version": "demo-A"
},
"reading": 420,
"sensorId": "demo-sensors-1",
"sensorName": "演示空气传感器",
"unit": "ppm"
},
{
"alarm": false,
"calibration": {
"points": [
0,
1000
],
"version": "demo-B"
},
"reading": 800,
"sensorId": "demo-sensors-2",
"sensorName": "演示光照传感器",
"unit": "lux"
}
],
"summary": {
"note": null,
"total": 2
}
},
"ok": true
}原例已核验,可修改输入后重新运行。
⌘ / Ctrl + Enter 运行01
场景与操作说明
传感器读数需要连同单位和校准条件解释。下面使用两条不同单位的读数,保留传感器标识、告警标记及校准点数组,练习数值提取与数据约束。
reading 是合成非负整数;真实温度等读数可能为负数,不能直接套用本例约束。
- 核对 传感器读数 的字段层级,保留 sensorId 的字符串类型。
- 修改一项输入并运行,观察结果中的值或路径如何变化。
- 载入对照样本,复现下面的变化;恢复原例会替换当前输入。
02
对照样本
对照样本反转 readings 数组。字段排序不会把数组自动排回去,核对输出中的首条 sensorId。
查看对照输入
{
"ok": true,
"data": {
"readings": [
{
"sensorId": "demo-sensors-2",
"sensorName": "演示光照传感器",
"reading": 800,
"alarm": false,
"unit": "lux",
"calibration": {
"version": "demo-B",
"points": [
0,
1000
]
}
},
{
"sensorId": "demo-sensors-1",
"sensorName": "演示空气传感器",
"reading": 420,
"alarm": true,
"unit": "ppm",
"calibration": {
"version": "demo-A",
"points": [
0,
100
]
}
}
],
"summary": {
"total": 2,
"note": null
}
}
}对照样本的实际结果
{
"data": {
"readings": [
{
"alarm": false,
"calibration": {
"points": [
0,
1000
],
"version": "demo-B"
},
"reading": 800,
"sensorId": "demo-sensors-2",
"sensorName": "演示光照传感器",
"unit": "lux"
},
{
"alarm": true,
"calibration": {
"points": [
0,
100
],
"version": "demo-A"
},
"reading": 420,
"sensorId": "demo-sensors-1",
"sensorName": "演示空气传感器",
"unit": "ppm"
}
],
"summary": {
"note": null,
"total": 2
}
},
"ok": true
}