我有这个 json 文件:
"[{\"id\":188457,\"title\":\"Painted Dragon Tea Mug with Lid\",\"slug\":\"painted-dragon-tea-mug-with-lid\",\"image\":\"https:\\\/\\\/thievemedia.imgix.net\\\/2018\\\/09\\\/painted-dragon-tea-mug-with-lid-featured-1.jpg\",\"full_image_url\":\"https:\\\/\\\/s3.amazonaws.com\\\/thieve-media\\\/wp-content\\\/uploads\\\/2018\\\/09\\\/painted-dragon-tea-mug-with-lid-featured-1.jpg\",\"large_image_url\":\"https:\\\/\\\/s3.amazonaws.com\\\/thieve-media\\\/wp-content\\\/uploads\\\/2018\\\/09\\\/painted-dragon-tea-mug-with-lid-featured-1.jpg\",\"medium_image_url\":\"https:\\\/\\\/s3.amazonaws.com\\\/thieve-media\\\/wp-content\\\/uploads\\\/2018\\\/09\\\/painted-dragon-tea-mug-with-lid-featured-1.jpg\",\"original_price\":\"19.78\",\"price\":\"13.65\",\"discount\":\"30.99\",\"rating\":\"4.7\",\"total_orders\":\"10\",\"promotion_url\":\"https:\\\/\\\/api.thieve.co\\\/view?id=MzI4NTk0Njg0MDE=\",\"product_like_count\":\"100\",\"product_user_likes\"}]
如何使用 jq 只提取标题?
答案1
该查询'.[] | {title}'
只会为您提供标题元素(但请注意,您的示例文档似乎格式不正确),假设您的文档位于名为的文件中data.json
:
$ jq '.[] | {title}' data.json
{
"title": "Painted Dragon Tea Mug with Lid"
}
查询的第一部分 ,'.[]'
返回顶级数组中的每个对象,然后使用运算符将这些对象发送到第二部分|
。查询的第二部分{title}
,简单地从对象中提取“title”元素。
如果您只想要字符串形式的标题,而不将结果包装在 JSON 对象中,请改用以下命令:
$ jq '.[] | .["title"]' data.json
"Painted Dragon Tea Mug with Lid"
这jq
教程提供了查询语言的良好概述。
答案2
假设输入是一个 JSON 字符串,对实际的 JSON 文档进行编码,您可以使用jq
该字符串将字符串解码为 JSON,然后title
从顶级数组中的每个元素中提取键的值:
jq -r 'fromjson[]|.title' file