Shell 从 JSON 对象获取键值对的脚本
Shell script to get key value pair from JSON object
我有一个 JSON 对象
{
"Men": [
"All Clothing",
"All Clothing",
"All footwear",
"All footwear",
"All Watches",
"All Watches",
"All Sunglasses",
"All Sunglasses"
],
"Electronics": [
"Mobiles",
"Tablets",
"Wearable Smart Devices",
"Mobile Accessories",
"Headphones and headsets",
"Tablet Accessories",
"Computer Accessories",
"Televisions",
"Large Appliances",
"Small Appliances",
"Kitchen Appliances",
"Personal Care",
"Audio and video",
"Laptop"
],
"Women": [
"Ethnic wear",
"Western wear",
"Lingerie & Sleep Wear",
"All Bags, Belts & Wallets",
"All jewellery",
"All Perfumes",
"Spectacle Frames",
"Beauty & Personal Care",
"The International Beauty Shop"
]
}
我想使用 jq 过滤器从此 object.m 获取键值对,但它不起作用。
keys=`jq 'keys' $categories`
$categories 是json对象的变量名。欢迎提出建议。
不太清楚你在问什么。如果 $categories
包含您的 JSON 数据,那么您需要以某种方式将其通过管道传输到 jq
。对于 Bash,您可以使用此处的字符串:
jq keys <<<"$categories"
或更传统(且便携)的管道:
printf '%s\n' "$categories" | jq keys
要将键的值捕获到变量中,请使用命令替换:
keys=$(jq 'keys' <<<"$categories")
(或 `backticks`
就像您的尝试;但现代符号更可取);
或者更好的是,以与您首先分配 categories
相同的方式获取此值。
我有一个 JSON 对象
{
"Men": [
"All Clothing",
"All Clothing",
"All footwear",
"All footwear",
"All Watches",
"All Watches",
"All Sunglasses",
"All Sunglasses"
],
"Electronics": [
"Mobiles",
"Tablets",
"Wearable Smart Devices",
"Mobile Accessories",
"Headphones and headsets",
"Tablet Accessories",
"Computer Accessories",
"Televisions",
"Large Appliances",
"Small Appliances",
"Kitchen Appliances",
"Personal Care",
"Audio and video",
"Laptop"
],
"Women": [
"Ethnic wear",
"Western wear",
"Lingerie & Sleep Wear",
"All Bags, Belts & Wallets",
"All jewellery",
"All Perfumes",
"Spectacle Frames",
"Beauty & Personal Care",
"The International Beauty Shop"
]
}
我想使用 jq 过滤器从此 object.m 获取键值对,但它不起作用。
keys=`jq 'keys' $categories`
$categories 是json对象的变量名。欢迎提出建议。
不太清楚你在问什么。如果 $categories
包含您的 JSON 数据,那么您需要以某种方式将其通过管道传输到 jq
。对于 Bash,您可以使用此处的字符串:
jq keys <<<"$categories"
或更传统(且便携)的管道:
printf '%s\n' "$categories" | jq keys
要将键的值捕获到变量中,请使用命令替换:
keys=$(jq 'keys' <<<"$categories")
(或 `backticks`
就像您的尝试;但现代符号更可取);
或者更好的是,以与您首先分配 categories
相同的方式获取此值。