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

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

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

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

示例工作台

在完整工具中打开 ↗
JSON 整理与类型生成pretty键排序
运行结果
{
  "data": {
    "summary": {
      "note": null,
      "total": 2
    },
    "users": [
      {
        "active": true,
        "displayName": "示例用户甲",
        "loginCount": 12,
        "profile": {
          "city": "杭州",
          "tags": [
            "new",
            "web"
          ]
        },
        "role": "reader",
        "userId": "demo-users-1"
      },
      {
        "active": false,
        "displayName": "示例用户乙",
        "loginCount": 0,
        "profile": {
          "city": "成都",
          "tags": [
            "mobile"
          ]
        },
        "role": "editor",
        "userId": "demo-users-2"
      }
    ]
  },
  "ok": true
}

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

⌘ / Ctrl + Enter 运行
01

场景与操作说明

用户列表通常同时包含标识、展示名称、状态和资料。联调时先区分展示字段与权限字段,不能用昵称替代用户标识。

loginCount 是示例累计登录次数;0 是有效值,不应当成字段缺失。

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

对照样本

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

查看对照输入
{
  "ok": true,
  "data": {
    "users": [
      {
        "userId": "demo-users-2",
        "displayName": "示例用户乙",
        "loginCount": 0,
        "active": false,
        "role": "editor",
        "profile": {
          "city": "成都",
          "tags": [
            "mobile"
          ]
        }
      },
      {
        "userId": "demo-users-1",
        "displayName": "示例用户甲",
        "loginCount": 12,
        "active": true,
        "role": "reader",
        "profile": {
          "city": "杭州",
          "tags": [
            "new",
            "web"
          ]
        }
      }
    ],
    "summary": {
      "total": 2,
      "note": null
    }
  }
}

对照样本的实际结果

{
  "data": {
    "summary": {
      "note": null,
      "total": 2
    },
    "users": [
      {
        "active": false,
        "displayName": "示例用户乙",
        "loginCount": 0,
        "profile": {
          "city": "成都",
          "tags": [
            "mobile"
          ]
        },
        "role": "editor",
        "userId": "demo-users-2"
      },
      {
        "active": true,
        "displayName": "示例用户甲",
        "loginCount": 12,
        "profile": {
          "city": "杭州",
          "tags": [
            "new",
            "web"
          ]
        },
        "role": "reader",
        "userId": "demo-users-1"
      }
    ]
  },
  "ok": true
}