Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse error: Invalid numeric literal at line 1, column 2 (bash)

I'm working with json in bash, but I'm getting this parse error:

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

What's wrong with this block of code?

jsonStr=$(cat << EOF
'{"key1": "value1", "key2": "value2", "key3": "value3"}'
EOF
)
jsonStr=$(jq 'del(.key3)' <<<"$jsonStr")
STRING="hello"
jsonStr=$(jq '. + {'"$STRING"': "value4"}' <<<"$jsonStr")
echo $jsonStr
like image 777
mehtaarn000 Avatar asked Apr 23 '26 18:04

mehtaarn000


1 Answers

The $(cat << EOF ...) construct is passing the single quotes along as part of the data, ie:

$ jsonStr=$(cat << EOF
'{"key1": "value1", "key2": "value2", "key3": "value3"}' 
EOF
)
$ echo "${jsonStr}"
'{"key1": "value1", "key2": "value2", "key3": "value3"}'

Notice the leading/trailing single quotes.

To get past the parsing error you want to get rid of the single quotes, eg:

$ jsonStr=$(cat << EOF
{"key1": "value1", "key2": "value2", "key3": "value3"}
EOF
)

# or

$ jsonStr='{"key1": "value1", "key2": "value2", "key3": "value3"}'

Both of the above give us:

$ echo "${jsonStr}"
{"key1": "value1", "key2": "value2", "key3": "value3"}

And now the jq/del works as expected:

$ jq 'del(.key3)' <<< "${jsonStr}"
{
  "key1": "value1",
  "key2": "value2"
}

And then the + operation also works:

$ STRING="hello"
$ jq 'del(.key3)' <<< "${jsonStr}"  | jq '. + {'"$STRING"': "value4"}'
{
  "key1": "value1",
  "key2": "value2",
  "hello": "value4"
}

Pulling this all together:

jsonStr='{"key1": "value1", "key2": "value2", "key3": "value3"}'
jsonStr=$(jq 'del(.key3)' <<< "${jsonStr}")
STRING="hello"
jsonStr=$(jq '. + {'"${STRING}"': "value4"}' <<< "${jsonStr}")
echo "${jsonStr}"

Which generates:

{
  "key1": "value1",
  "key2": "value2",
  "hello": "value4"
}
like image 60
markp-fuso Avatar answered Apr 25 '26 07:04

markp-fuso