0

I have this json file:

"[{\"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\"}]

How can I extract only the titles with jq?

  • That's not valid JSON -- it is a JS string containing escape sequences, so you'll first have to remove those escapes with eg. sed 's/^"//;s/"$//;s/\\\(.\)/\1/g' – JigglyNaga Oct 9 '18 at 18:51
2

The query '.[] | {title}' will give you just the title elements (but note that your sample document seems to be malformed), assuming your document is in a file called data.json:

$ jq '.[] | {title}' data.json
{
    "title": "Painted Dragon Tea Mug with Lid"
}

The first part of the query, '.[]', returns each object in the top-level array, and these are then sent to the second part, using the | operator. The second part of the query, {title}, simply extracts the "title" element from the object.

If you want just the title, as a string, without wrapping the results in a JSON object, use this instead:

$ jq '.[] | .["title"]' data.json
"Painted Dragon Tea Mug with Lid"

The jq tutorial offers a good overview of the query language.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.