英文:
JQ transform JSON doc
问题
You can achieve this transformation using jq
in a Linux environment. Here's the jq
command you can use:
jq '.key1 |= [.[0] + "-" + .[1]], .key2 |= [.[0] + "-" + .[1]]' your_json_file.json
Replace your_json_file.json
with the path to your JSON file. This command will modify the JSON by concatenating the values of "key1" and "key2" with a hyphen ("-").
英文:
I have JSON file with below format
{
"key1": ["val1", "val2"],
"key2": ["v1", "v2"]
}
I want to transform it into
{
"key1": ["val1-v1", "val2-v2"],
"key2": ["v1", "v2"]
}
How can I acheive this using jq in linux environment?
答案1
得分: 0
你可以使用 to_entries
生成索引和值的数组。使用这些索引来访问存储在变量中的其他键:
jq '. as {$key2} | .key1 |= [to_entries[] | .value + "-" + $key2[.key]]' data.json
如果数组不是很大,你也可以使用效率较低的 transpose
过滤器来进行合并:
jq '.key1 = [map(.) | transpose[] | join("-")]' data.json
两者的输出:
{
"key1": [
"val1-v1",
"val2-v2"
],
"key2": [
"v1",
"v2"
]
}
英文:
You could use to_entries
to generate an array of indices and values. Use the indices to index into the other key, stored in a variable for reference:
jq '. as {$key2} | .key1 |= [to_entries[] | .value + "-" + $key2[.key]]' data.json
If the arrays aren't big, you could also use the less efficient transpose
filter to zip them:
jq '.key1 = [map(.) | transpose[] | join("-")]' data.json
Output of both:
{
"key1": [
"val1-v1",
"val2-v2"
],
"key2": [
"v1",
"v2"
]
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论