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

权限清单:递归排序对象字段并保留数组顺序

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

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

示例工作台

在完整工具中打开 ↗
JSON 整理与类型生成pretty键排序
运行结果
{
  "data": {
    "grants": [
      {
        "grantId": "demo-permissions-1",
        "granted": true,
        "policy": {
          "actions": [
            "read"
          ],
          "owner": "demo-team"
        },
        "priority": 1,
        "resource": "演示文档空间",
        "scope": "team"
      },
      {
        "grantId": "demo-permissions-2",
        "granted": false,
        "policy": {
          "actions": [
            "read",
            "write"
          ],
          "owner": "demo-project"
        },
        "priority": 2,
        "resource": "演示项目仓库",
        "scope": "project"
      }
    ],
    "summary": {
      "note": null,
      "total": 2
    }
  },
  "ok": true
}

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

⌘ / Ctrl + Enter 运行
01

场景与操作说明

权限清单中的声明不能替代服务端授权判断。合成规则只帮助检查字段和差异,不会为账号授予权限。

priority 是示例规则排序值,不表示用户的安全级别。

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

对照样本

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

查看对照输入
{
  "ok": true,
  "data": {
    "grants": [
      {
        "grantId": "demo-permissions-2",
        "resource": "演示项目仓库",
        "priority": 2,
        "granted": false,
        "scope": "project",
        "policy": {
          "actions": [
            "read",
            "write"
          ],
          "owner": "demo-project"
        }
      },
      {
        "grantId": "demo-permissions-1",
        "resource": "演示文档空间",
        "priority": 1,
        "granted": true,
        "scope": "team",
        "policy": {
          "actions": [
            "read"
          ],
          "owner": "demo-team"
        }
      }
    ],
    "summary": {
      "total": 2,
      "note": null
    }
  }
}

对照样本的实际结果

{
  "data": {
    "grants": [
      {
        "grantId": "demo-permissions-2",
        "granted": false,
        "policy": {
          "actions": [
            "read",
            "write"
          ],
          "owner": "demo-project"
        },
        "priority": 2,
        "resource": "演示项目仓库",
        "scope": "project"
      },
      {
        "grantId": "demo-permissions-1",
        "granted": true,
        "policy": {
          "actions": [
            "read"
          ],
          "owner": "demo-team"
        },
        "priority": 1,
        "resource": "演示文档空间",
        "scope": "team"
      }
    ],
    "summary": {
      "note": null,
      "total": 2
    }
  },
  "ok": true
}