13

I'm doing a curl like the following

curl -X GET "https://api.mercadolibre.com/items/MLA511127356"

and the response is a JSON, like for example this one:

"id": "MLA511127356",
  "site_id": "MLA",
  "title": "Item De Testeo, Por Favor No Ofertar --kc:off",
  "subtitle": null,
  "seller_id": "160252486",
  "category_id": "MLA4967",
  "official_store_id": null,
  "price": 10,
  "base_price": 10,
  "original_price": null,
  "currency_id": "ARS",
  "initial_quantity": 16,

Is there a simple way to do this?

Thank you!

3fff
  • 131
  • 1
  • 1
  • 5

3 Answers3

15

By using jq you could parse the json data instead of the text based parsing.

curl -X GET "https://api.mercadolibre.com/items/MLA511127356" | jq '.[].id'
visibilityspots
  • 153
  • 1
  • 7
10

As mentioned here you can use grep -Po '"keyThatYouWant":.*?[^\\]",' file.json. Like that:

local result=$(curl -X GET $YOUR_HUGE_URL)
echo $result | grep -Po '"keyThatYouWant":.*?[^\\]",'
Community
  • 1
  • 1
R. Karlus
  • 2,094
  • 3
  • 24
  • 48
9

jq is pretty impressive but if you do not want to install another dependency, using python is a nice alternative by also giving you some extra flexibility if further processing is desired.

Jist of it is to pipe the json curl result to python -c.

Example:

curl -X GET https://jsonplaceholder.typicode.com/comments/4 | python -c "import sys,json; print json.load(sys.stdin)['email']"
Theuns Alberts
  • 330
  • 4
  • 7
  • 1
    This is almost perfect for my needs. However, I'm at a loss as to why everything has single quotes, and is therefore not valid JSON. When I find an answer to that I'll comment further. Okay, found it: Wrap `json.load(sys.stdn)['email]` with `json.dumps(json.load(sys.stdn)['email])` (this also works with a final out file ` > results.json` - per my own needs) – Neil Gaetano Lindberg Oct 10 '19 at 15:57