JSON.CN让代码更轻
JSON 整理与类型生成可运行案例

设备列表:递归排序对象字段并保留数组顺序

递归按键名整理对象,便于人工检查。devices 的数组顺序不变;排序后的 JSON 文本不能直接当作通用签名规范或所有语言一致的 canonical JSON。

浏览器本地处理合成数据同场景 32 个案例 ↗

示例工作台

在完整工具中打开 ↗
JSON 整理与类型生成pretty键排序
运行结果
{
  "data": {
    "devices": [
      {
        "battery": 85,
        "connection": "wifi",
        "deviceId": "demo-devices-1",
        "hardware": {
          "firmware": "demo-1.0",
          "ports": [
            "usb"
          ]
        },
        "modelName": "演示传感终端",
        "online": true
      },
      {
        "battery": 100,
        "connection": "ethernet",
        "deviceId": "demo-devices-2",
        "hardware": {
          "firmware": "demo-2.0",
          "ports": [
            "lan",
            "usb"
          ]
        },
        "modelName": "演示网关设备",
        "online": false
      }
    ],
    "summary": {
      "note": null,
      "total": 2
    }
  },
  "ok": true
}

原例已核验,可修改输入后重新运行。

⌘ / Ctrl + Enter 运行
01

场景与操作说明

设备在线标记是采样时刻的状态,不能说明设备现在仍在线。此案例不扫描网络或连接任何设备。

battery 为演示百分比;网关的 100 只是样本值,不表示真实电源检测。

  1. 核对 设备列表 的字段层级,保留 deviceId 的字符串类型。
  2. 修改一项输入并运行,观察结果中的值或路径如何变化。
  3. 载入对照样本,复现下面的变化;恢复原例会替换当前输入。
02

对照样本

对照样本反转 devices 数组。字段排序不会把数组自动排回去,核对输出中的首条 deviceId。

查看对照输入
{
  "ok": true,
  "data": {
    "devices": [
      {
        "deviceId": "demo-devices-2",
        "modelName": "演示网关设备",
        "battery": 100,
        "online": false,
        "connection": "ethernet",
        "hardware": {
          "firmware": "demo-2.0",
          "ports": [
            "lan",
            "usb"
          ]
        }
      },
      {
        "deviceId": "demo-devices-1",
        "modelName": "演示传感终端",
        "battery": 85,
        "online": true,
        "connection": "wifi",
        "hardware": {
          "firmware": "demo-1.0",
          "ports": [
            "usb"
          ]
        }
      }
    ],
    "summary": {
      "total": 2,
      "note": null
    }
  }
}

对照样本的实际结果

{
  "data": {
    "devices": [
      {
        "battery": 100,
        "connection": "ethernet",
        "deviceId": "demo-devices-2",
        "hardware": {
          "firmware": "demo-2.0",
          "ports": [
            "lan",
            "usb"
          ]
        },
        "modelName": "演示网关设备",
        "online": false
      },
      {
        "battery": 85,
        "connection": "wifi",
        "deviceId": "demo-devices-1",
        "hardware": {
          "firmware": "demo-1.0",
          "ports": [
            "usb"
          ]
        },
        "modelName": "演示传感终端",
        "online": true
      }
    ],
    "summary": {
      "note": null,
      "total": 2
    }
  },
  "ok": true
}