JQ 转换 JSON 文档

huangapple go评论57阅读模式
英文:

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

Demo

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

Demo

Output of both:

{
  "key1": [
    "val1-v1",
    "val2-v2"
  ],
  "key2": [
    "v1",
    "v2"
  ]
}

huangapple
  • 本文由 发表于 2023年5月21日 11:21:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298165.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定