如何使用jq更新json数组中的每个对象

问题描述 投票:0回答:1

我有一个看起来像这样的对象数组:

[
    {"host": "1.exampl.com", "path": "/dir1/file.html"},
    {"host": "2.exampl.com", "path": "/dir2/file.html"},
    {"host": "3.exampl.com", "path": "/dir3/file.html"}
]

我想在每个对象中添加一个新键,这将使用主机和路径创建 URL,所以我看起来像这样:

[
    {"host": "1.exampl.com", "path": "/dir1/file.html", "url": "http://1.example.com/dir1/file.html"},
    {"host": "2.exampl.com", "path": "/dir2/file.html", "url": "http://2.example.com/dir2/file.html"},
    {"host": "3.exampl.com", "path": "/dir3/file.html", "url": "http://3.example.com/dir3/file.html"}
]

我怎样才能使用

jq
做到这一点。

我尝试做

".[] |= . { . + {\"url\": \"http://\" + .host + .path } }"
但这不起作用并返回此错误:
jq: error: syntax error, unexpected '}', expecting $end (Unix shell quoting issues?) at <top-level>, line 1:

jq
1个回答
0
投票

在您的过滤器中,部分

. { . + {
在 jq 中无效。

尝试以下过滤器之一:

.[] |= (.url = "http://" + .host + .path)
map(.url = "http://" + .host + .path)
.[] |= (.url = "http://\(.host)\(.path)")
map(.url = "http://\(.host)\(.path)")
© www.soinside.com 2019 - 2024. All rights reserved.