TransWikia.com

curl jq get value from field name

Unix & Linux Asked on December 6, 2021

created=$(curl  -i -X POST -H 'Content-Type:application/json' --data "$(payload)"  https://myurl/resource)

The above return a json object

{
  "revision": {
    "clientId": "",
    "version": 1,
    "lastModifier": "admin"
  },
  "id": "idvalue",
  "uri": "https://myurl/idvalue",
  "position": {
    "x": 100,
    "y": 200
  }
}

I am using the below code to get id from above object

idvar=$(echo $created | jq ' .id' )

but the above gives me the below error

parse error: Invalid numeric literal at line 1, column 9

2 Answers

The response that you get from curl will contain HTTP headers, because you request these with -i (--include). This means that the contents of your created variable will contain HTTP headers, then some JSON.

The jq tool can not parse HTTP headers, so it complains. A standard HTTP response header starts with something like HTTP/1.1 200 OK. The location "line 1, column 9" happens to be where this string has its first space character, which is where the JSON parser gives up and reports an error.

Removing the -i option from the curl invocation should make your code work, although if you just need the value of the id key, there is really no need to store the output of curl in an intermediate variable:

curl -X POST 
    --header 'Content-Type:application/json' 
    --data "$json_document" 'https://myurl/resource' |
jq .id

Answered by Kusalananda on December 6, 2021

If you remove the space from your query string it works:

$ idvar=$(echo $created | jq '.id' )
$ echo $idvar
"idvalue"
$

I would consider using jp from JMESpath (https://github.com/jmespath/jp) as it has a better precisely defined language syntax.

$ echo $created | jp "id"
"idvalue"
$

Answered by JdeHaan on December 6, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP