You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在MarkLogic中基于JSON文档内数组大小查询或排序文档?

按phone数组长度排序JSON文档

假设你有一组包含phone数组的JSON对象(示例如下),需要按phone数组的长度大小排序:

[
{
"name": "ruby",
"phone": [
{"type": "mobile", "number": 12345678},
{"type": "office", "number": 2433242}
]
},
{
"name": "alice",
"phone": [
{"type": "mobile", "number": 98765432}
]
},
{
"name": "bob",
"phone": [
{"type": "mobile", "number": 11111111},
{"type": "office", "number": 22222222},
{"type": "home", "number": 33333333}
]
}
]

以下是两种常用编程语言的实现方式:

Python实现

利用sorted()函数,以每个对象中phone数组的长度作为排序依据:

import json

# 加载JSON数据
json_data = '''
[
  {"name": "ruby", "phone": [{"type": "mobile", "number": 12345678}, {"type": "office", "number": 2433242}]},
  {"name": "alice", "phone": [{"type": "mobile", "number": 98765432}]},
  {"name": "bob", "phone": [{"type": "mobile", "number": 11111111}, {"type": "office", "number": 22222222}, {"type": "home", "number": 33333333}]}
]
'''
data = json.loads(json_data)

# 升序排序(数组长度从小到大)
sorted_asc = sorted(data, key=lambda x: len(x['phone']))
# 降序排序(数组长度从大到小)
sorted_desc = sorted(data, key=lambda x: len(x['phone']), reverse=True)

# 输出格式化后的结果
print("升序排序结果:")
print(json.dumps(sorted_asc, indent=2))
print("\n降序排序结果:")
print(json.dumps(sorted_desc, indent=2))

JavaScript实现

使用Array.sort()方法,通过比较两个对象的phone数组长度完成排序:

// 定义JSON数据数组
const jsonData = [
  {"name": "ruby", "phone": [{"type": "mobile", "number": 12345678}, {"type": "office", "number": 2433242}]},
  {"name": "alice", "phone": [{"type": "mobile", "number": 98765432}]},
  {"name": "bob", "phone": [{"type": "mobile", "number": 11111111}, {"type": "office", "number": 22222222}, {"type": "home", "number": 33333333}]}
];

// 升序排序
const sortedAsc = [...jsonData].sort((a, b) => a.phone.length - b.phone.length);
// 降序排序
const sortedDesc = [...jsonData].sort((a, b) => b.phone.length - a.phone.length);

// 打印结果
console.log("升序排序结果:", JSON.stringify(sortedAsc, null, 2));
console.log("\n降序排序结果:", JSON.stringify(sortedDesc, null, 2));

内容的提问来源于stack exchange,提问作者Ruby Kannan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 05:05:36