我有一个对象的 JSON 对象:
{
"lungCancerCellLines": {
"componentIndex": 11,
"active": true,
"longName": "Lung cancer cell lines",
"filenameKey": "lungCancerCellLines",
"color": "#8CC63F"
},
"naturalKillerCells": {
"componentIndex": 1,
"active": true,
"longName": "Natural killer cells",
"filenameKey": "naturalKillerCells",
"color": "#BB2DD4"
},
"respiratoryMuscular": {
"componentIndex": 12,
"active": true,
"longName": "Respiratory / muscular",
"filenameKey": "respiratoryMuscular",
"color": "#DDE223"
},
"cerebellarHemisphere": {
"componentIndex": 14,
"active": true,
"longName": "Cerebellar hemisphere",
"filenameKey": "cerebellarHemisphere",
"color": "#2E97BC"
},
"bCells": {
"componentIndex": 2,
"active": true,
"longName": "B cells",
"filenameKey": "bCells",
"color": "#E6009B"
},
...,
"cd34PlusProgenitor": {
"componentIndex": 8,
"active": true,
"longName": "CD34+ progenitor",
"filenameKey": "cd34PlusProgenitor",
"color": "#ED2024"
}
}
我想按照
componentIndex
(升序)顺序编写一个JSON对象。
根据之前的 Stack Overflow 问题和答案,我尝试了以下陈述:
jq -s 'sort_by(.[].componentIndex)' in.json > out.v1.json
并且:
jq -s 'sort_by(.[].componentIndex|tonumber)' in.json > out.v2.json
文件
out.v1.json
和 out.v2.json
与 in.json
的显示顺序相同。
按所需排序顺序提供嵌套对象的正确
jq
语句是什么?
我要问的真正问题是如何按照
color
中的整数提供的顺序提取 componentIndex
键的值。但作为第一步,看起来我需要解决如何使用 jq
对整数值进行排序。谢谢你的建议。
对象字段没有顺序,数组项有。如果要将对象转为数组,请使用
map(.)
或 [.[]]
,然后 sort_by(.componentIndex)
会对数组进行排序。 (请注意,.componentIndex
已经是一个数字,因此.componentIndex|tonumber
不会改变任何内容。)
也就是说,由于 JSON 编码只是字符流,您当然可以在对象内创建顺序,但请记住,这只是实际文件中的表示形式。顺序绝不会编码到 JSON 文档中,只是在保存时恰好有一个。任何 JSON 处理器都可以重新排列该顺序,恕不另行通知。这包括(未来版本)jq。
从 jq 的当前版本开始,您可以欺骗它在对象内生成该顺序,方法是首先将其转换为数组,然后对其进行排序,然后使用数组的顺序重新组装对象。
jq 'to_entries | sort_by(.value.componentIndex) | from_entries'
{
"naturalKillerCells": {
"componentIndex": 1,
"active": true,
"longName": "Natural killer cells",
"filenameKey": "naturalKillerCells",
"color": "#BB2DD4"
},
"bCells": {
"componentIndex": 2,
"active": true,
"longName": "B cells",
"filenameKey": "bCells",
"color": "#E6009B"
},
"cd34PlusProgenitor": {
"componentIndex": 8,
"active": true,
"longName": "CD34+ progenitor",
"filenameKey": "cd34PlusProgenitor",
"color": "#ED2024"
},
"lungCancerCellLines": {
"componentIndex": 11,
"active": true,
"longName": "Lung cancer cell lines",
"filenameKey": "lungCancerCellLines",
"color": "#8CC63F"
},
"respiratoryMuscular": {
"componentIndex": 12,
"active": true,
"longName": "Respiratory / muscular",
"filenameKey": "respiratoryMuscular",
"color": "#DDE223"
},
"cerebellarHemisphere": {
"componentIndex": 14,
"active": true,
"longName": "Cerebellar hemisphere",
"filenameKey": "cerebellarHemisphere",
"color": "#2E97BC"
}
}