我有几个 JSON 文件,结构略有不同(可以有多个“列”)
但它们看起来像这样:
[{"data":"redacted1","type":"unknown"},{"data":"","type":"unknown"},{"data":"[email protected]","type":"email"}]
[{"data":"redacted2","type":"unknown"},{"data":"","type":"unknown"},{"data":"[email protected]","type":"email"}]
[{"data":"redacted3","type":"unknown"},{"data":"","type":"unknown"},{"data":"[email protected]","type":"email"}]
我想用我自己的值替换“类型”,第三个数据指针是电子邮件,第一个是名称,中间的是垃圾邮件,第三个已经有值了。
所以我希望它看起来像这样:
[{"data":"redacted1","type":"name"},{"data":"","type":"junk"},{"data":"[email protected]","type":"email"}]
[{"data":"redacted2","type":"name"},{"data":"","type":"junk"},{"data":"[email protected]","type":"email"}]
[{"data":"redacted3","type":"name"},{"data":"","type":"junk"},{"data":"[email protected]","type":"email"}]
我如何使用 JQ 来实现这一点?
答案1
鉴于
$ cat file.json
[{"data":"redacted1","type":"unknown"},{"data":"","type":"unknown"},{"data":"[email protected]","type":"email"}]
[{"data":"redacted2","type":"unknown"},{"data":"","type":"unknown"},{"data":"[email protected]","type":"email"}]
[{"data":"redacted3","type":"unknown"},{"data":"","type":"unknown"},{"data":"[email protected]","type":"email"}]
然后
$ jq -c '.[0].type = "name" | .[1].type = "junk"' file.json
[{"data":"redacted1","type":"name"},{"data":"","type":"junk"},{"data":"[email protected]","type":"email"}]
[{"data":"redacted2","type":"name"},{"data":"","type":"junk"},{"data":"[email protected]","type":"email"}]
[{"data":"redacted3","type":"name"},{"data":"","type":"junk"},{"data":"[email protected]","type":"email"}]