Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting data from json using jq when key is numerical string

Tags:

json

bash

jq

I am new to jq and facing an issue while parsing my json

I have a json stored in a variable like this

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

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

I have tried something like this

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

And similarly to get my_name value I did

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

Can any one please help to identify what is wrong with my syntax and how can I correct it.

like image 973
user2243651 Avatar asked Mar 03 '15 23:03

user2243651


People also ask

How do you escape a dot in jq?

Put the key first in double quotes and then escape the first dot by wrapping it using single quotes.

What does jq command do?

The JQ command is used to transform JSON data into a more readable format and print it to the standard output on Linux. The JQ command is built around filters which are used to find and print only the required data from a JSON file.


1 Answers

Just the number gets interpreted as a float. You need to use it in a context where it is unambiguously a key string.

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

and

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

to get the containing dict.

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

echo "$temp" | jq '."1".my_name'
like image 97
tripleee Avatar answered Oct 14 '22 22:10

tripleee