如何使用jq将键值对对象转换为指定结构的数组
Answer
Absolutely! You can use jq's to_entries function to convert your key-value object into an array of structured entries, then reshape each entry to match your desired format.
Here's the jq command that gets the job done:
jq 'to_entries | map({key: .key} + .value)' input.json
How this works step-by-step:
to_entries: This transforms your original object into an array of{key, value}pairs. For your input, this produces:[ { "key": "alpha", "value": { "bytes": { "value": 4789440 }, "doc_count": 7723 } }, { "key": "beta", "value": { "bytes": { "value": 4416862639 }, "doc_count": 1296 } } ]map({key: .key} + .value): For each entry in the array, we merge thekeyfield with all properties from thevalueobject. This combines them into the exact structure you requested.
Example Output:
Running the command on your input will output:
[ { "key": "alpha", "bytes": { "value": 4789440 }, "doc_count": 7723 }, { "key": "beta", "bytes": { "value": 4416862639 }, "doc_count": 1296 } ]
This method is flexible—it works for any number of top-level keys in your original object, not just "alpha" and "beta".
内容的提问来源于stack exchange,提问作者sontags
相关产品推荐
相关产品推荐

