我需要按自然順序的鍵對以下 JSON 檔案進行排序,但“必需”部分中列出的鍵應該首先出現,該怎么做?
以下命令僅按按自然順序排列的鍵進行排序:
jq --sort-keys . /tmp/source.json > ./tmp/target.json
{
"Request": {
"properties": {
"capacity": {
"$ref": "SubscriptionCapacity"
},
"metadata": {
"$ref": "MeterDefinitionsAndPolicy"
},
"data": {
"type": "string"
},
"avs": {
"pattern": "standard:v2",
"type": "string"
}
},
"required": [
"data",
"avs"
],
"type": "object"
}
}
預期的輸出應該是這樣的:
{
"Request": {
"properties": {
"avs": {
"$ref": "Pricing"
},
"data": {
"type": "string"
}
"capacity": {
"$ref": "SubscriptionCapacity"
},
"metadata": {
"$ref": "MeterDefinitionsAndPolicy"
}
},
"required": [
"data",
"avs"
],
"type": "object"
}
}
uj5u.com熱心網友回復:
keys這是一種直接且相當有效的方法,它利用了將鍵名生成為排序陣列的事實:
. as $in
| .Request
| (.required|sort) as $required
| (.properties|keys) as $all
| ($all - $required) as $optional
| .properties as $p
| $in
| .Request.properties = reduce ($required[], $optional[]) as $key ({}; . {($key): $p[$key]} )
請注意,gojq,即 jq 的 Go 實作,確實支持keys但通常不尊重用戶指定的物件內鍵的順序。
uj5u.com熱心網友回復:
你可以按照以下方式做一些事情
.Request.required as $req
| .Request.properties |= (
to_entries
| sort_by(.key)
| group_by(IN(.key; $req[]) | not)
| map(from_entries)
| add
)
{
"Request": {
"properties": {
"avs": {
"pattern": "standard:v2",
"type": "string"
},
"data": {
"type": "string"
},
"capacity": {
"$ref": "SubscriptionCapacity"
},
"metadata": {
"$ref": "MeterDefinitionsAndPolicy"
}
},
"required": [
"data",
"avs"
],
"type": "object"
}
}
演示
但是您不能保證在任何后續處理之后訂單將保持不變,因為物件通常沒有訂單,陣列有。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/410025.html
標籤:
下一篇:Python嵌套字典訪問問題
