2
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
pLumo
  • 22,231
  • 2
  • 41
  • 66
HDev007
  • 261
  • 1
  • 4
  • 10
  • Works fine for me with your json from the question, I guess we don't see the json you're using. But anyways, you should double quote your variables. And also you might want to [prefer `printf` over `echo`](https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo). – pLumo Jul 23 '20 at 06:29
  • removing -i from curl worked for me @pLumo – HDev007 Jul 23 '20 at 08:36

2 Answers2

0

The response 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, 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
Kusalananda
  • 320,670
  • 36
  • 633
  • 936
-1

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"
$
JdeHaan
  • 914
  • 1
  • 6
  • 20