如何使用 bash 从 json 中检索 "name" 值?
How to retrieve "name" value from json using bash?
我正在使用以下 curl 命令:
curl -s -v --user admin:orca --insecure -X GET https://insecure.registry.com/api/v0/repositories/authi-api/tags
获得以下输出:
{
"name": "Dev_ReleaseRollout_Lane-3",
"inRegistry": true,
"hashMismatch": false,
"inNotary": false
},
{
"name": "Dev_ReleaseRollout_Lane-latest",
"inRegistry": true,
"hashMismatch": false,
"inNotary": false
},
{
"name": "Payments_Dev_Lane-267",
"inRegistry": true,
"hashMismatch": false,
"inNotary": false
}
我只想获取变量中的 name
个值。
我只需要 Dev_ReleaseRollout_Lane-3
Dev_ReleaseRollout_Lane-latest
Payments_Dev_Lane-267
变量
假设您实际上有一个围绕三个对象的数组:
$ curl ... | jq -r '.[].name'
Dev_ReleaseRollout_Lane-3
Dev_ReleaseRollout_Lane-latest
Payments_Dev_Lane-267
很简单,.
是数组,[].name
从数组中的每个元素取名。 -r
是原始输出。
--raw-output / -r:
With this option, if the filter’s result is a string then it will be written directly to standard output rather than being formatted as a JSON string with quotes. This can be useful for making jq filters talk to non-JSON-based systems.
如果 cURL 输出实际上如上所述,则以下将起作用:
jq -rRs '"[\(.)]" | fromjson[].name' file.json
不过我认为有一种更好的方法可以将数组包裹在输入周围,
-R
是原始输入,-s
是 slurp。 \(...)
是 string interpolation.
--slurp/-s:
Instead of running the filter for each JSON object in the input, read the entire input stream into a large array and run the filter just once.
我正在使用以下 curl 命令:
curl -s -v --user admin:orca --insecure -X GET https://insecure.registry.com/api/v0/repositories/authi-api/tags
获得以下输出:
{
"name": "Dev_ReleaseRollout_Lane-3",
"inRegistry": true,
"hashMismatch": false,
"inNotary": false
},
{
"name": "Dev_ReleaseRollout_Lane-latest",
"inRegistry": true,
"hashMismatch": false,
"inNotary": false
},
{
"name": "Payments_Dev_Lane-267",
"inRegistry": true,
"hashMismatch": false,
"inNotary": false
}
我只想获取变量中的 name
个值。
我只需要 Dev_ReleaseRollout_Lane-3
Dev_ReleaseRollout_Lane-latest
Payments_Dev_Lane-267
变量
假设您实际上有一个围绕三个对象的数组:
$ curl ... | jq -r '.[].name'
Dev_ReleaseRollout_Lane-3
Dev_ReleaseRollout_Lane-latest
Payments_Dev_Lane-267
很简单,.
是数组,[].name
从数组中的每个元素取名。 -r
是原始输出。
--raw-output / -r:
With this option, if the filter’s result is a string then it will be written directly to standard output rather than being formatted as a JSON string with quotes. This can be useful for making jq filters talk to non-JSON-based systems.
如果 cURL 输出实际上如上所述,则以下将起作用:
jq -rRs '"[\(.)]" | fromjson[].name' file.json
不过我认为有一种更好的方法可以将数组包裹在输入周围,
-R
是原始输入,-s
是 slurp。 \(...)
是 string interpolation.
--slurp/-s:
Instead of running the filter for each JSON object in the input, read the entire input stream into a large array and run the filter just once.