Getting data from json using jq when key is a numeric string

I am new to jq and am encountering a problem while parsing my json

I have json stored in a variable like this

temp='{ "1": { "my_name": "one" }, "2": { "my_name": "two" } }' 

Now I need to get the value my_name for both other entries

I tried something like this

 echo $temp | jq '.1' //out put 0.1 I was assuming to get { "my_name": "one" } 

And similarly, to get the value of my_name, I did

 echo $temp | jq '.1.my_name' // Its output is giving me error 

Can anyone help determine what is wrong with my syntax and how can I fix it.

thanks

+5
source share
2 answers

Just the number is interpreted as a float. You should use it in a context where it is uniquely the key string.

 echo "$temp" | jq '.["1"]["my_name"]' 

and

 echo "$temp" | jq '.["1"]' 

to get containing a dict.

With a fairly new jq (I think> = 1.4) you can also say

 echo "$temp" | jq '."1".my_name' 
+5
source

Whenever you try to refer to a key that is not a valid identifier, you should quote it. See manual for more details.

To select an item under key 1 , you must do the following:

 ."1" 

For your other question on how to get my_name values, you can do this:

 to_entries | map(.value.my_name) 
+1
source

Source: https://habr.com/ru/post/1214622/


All Articles