简体   繁体   English

使用 jq 如何用其他东西替换键的名称

[英]Using jq how can I replace the name of a key with something else

This should be easy enough... I want to rename a few keys (ideally with jq), whatever I do seems to error though.这应该很容易...我想重命名几个键(最好用 jq),但无论我做什么似乎都会出错。 Here is a json example below:下面是一个 json 示例:

[
 {
  "fruit": "strawberry",
  "veg": "apple",
  "worker": "gardener"
 }
]

I'd like to rename the veg key to fruit2 (or example, whatever is easiest) and also the worker key to job.我想将 veg 键重命名为fruit2(或例如,任何最简单的)以及工作的工人键。

I realize this is possible in sed, but I'm trying to get to grips with jq我意识到这在 sed 中是可能的,但我正在努力掌握 jq

Use the following jq approach:使用以下jq方法:

jq '[.[] | .["fruit2"] = .veg | .["job"] = .worker | del(.veg, .worker)]' file

The output:输出:

[
  {
    "fruit": "strawberry",
    "fruit2": "apple",
    "job": "gardener"
  }
]

The key (:-) is with_entries.关键 (:-) 是 with_entries。 Eg, given a single object:例如,给定一个对象:

with_entries(if .key == "veg" then .key = "fruit2" else . end)

In your case, since you have an array of objects, you could wrap the above in map( ... ) .在您的情况下,由于您有一个对象数组,您可以将上述内容包装在map( ... )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM