JSON 整理与类型生成可运行案例
消息通知:递归排序对象字段并保留数组顺序
递归按键名整理对象,便于人工检查。notifications 的数组顺序不变;排序后的 JSON 文本不能直接当作通用签名规范或所有语言一致的 canonical JSON。
试一试
在完整工具中打开 ↗示例工作台
JSON 整理与类型生成
pretty键排序运行结果
{
"data": {
"notifications": [
{
"audience": {
"groups": [
"demo-team"
],
"locale": "zh-CN"
},
"channel": "inbox",
"messageId": "demo-notifications-1",
"read": true,
"retryCount": 0,
"subject": "演示站内消息"
},
{
"audience": {
"groups": [
"demo-test"
],
"locale": "en"
},
"channel": "push",
"messageId": "demo-notifications-2",
"read": false,
"retryCount": 2,
"subject": "演示推送消息"
}
],
"summary": {
"note": null,
"total": 2
}
},
"ok": true
}原例已核验,可修改输入后重新运行。
⌘ / Ctrl + Enter 运行01
场景与操作说明
通知渠道、已读标记和重试次数表达不同状态。下面的站内消息和推送消息各有受众分组与语言设置,可练习提取消息标识、校验布尔状态,以及核对重试计数的类型。
retryCount 是示例重试次数,已读状态不由该次数推出。
- 核对 消息通知 的字段层级,保留 messageId 的字符串类型。
- 修改一项输入并运行,观察结果中的值或路径如何变化。
- 载入对照样本,复现下面的变化;恢复原例会替换当前输入。
02
对照样本
对照样本反转 notifications 数组。字段排序不会把数组自动排回去,核对输出中的首条 messageId。
查看对照输入
{
"ok": true,
"data": {
"notifications": [
{
"messageId": "demo-notifications-2",
"subject": "演示推送消息",
"retryCount": 2,
"read": false,
"channel": "push",
"audience": {
"groups": [
"demo-test"
],
"locale": "en"
}
},
{
"messageId": "demo-notifications-1",
"subject": "演示站内消息",
"retryCount": 0,
"read": true,
"channel": "inbox",
"audience": {
"groups": [
"demo-team"
],
"locale": "zh-CN"
}
}
],
"summary": {
"total": 2,
"note": null
}
}
}对照样本的实际结果
{
"data": {
"notifications": [
{
"audience": {
"groups": [
"demo-test"
],
"locale": "en"
},
"channel": "push",
"messageId": "demo-notifications-2",
"read": false,
"retryCount": 2,
"subject": "演示推送消息"
},
{
"audience": {
"groups": [
"demo-team"
],
"locale": "zh-CN"
},
"channel": "inbox",
"messageId": "demo-notifications-1",
"read": true,
"retryCount": 0,
"subject": "演示站内消息"
}
],
"summary": {
"note": null,
"total": 2
}
},
"ok": true
}