21

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.

3
  • 2
    please edit your question to include the exact command and error message you are getting. Also, i shell programming, it is a good rule-of-thumb to quote any variable use (except for a very few special cases). echo "$temp" | ... may help. Good luck. Commented Mar 3, 2015 at 23:55
  • Hi @shellter wrapping it around the quotes is still giving the same result. Commented Mar 4, 2015 at 1:52
  • my comment about echo "$temp" is meant to be a general bit of advice. I didn't mean to say it would solve your problem. I believe the 1 upvote for my comment is for my request that you edit your question to include exact command you are executing AND exact text of error message you are getting. Good luck. Commented Mar 4, 2015 at 3:00

2 Answers 2

21

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'
Sign up to request clarification or add additional context in comments.

Comments

6

Whenever you are trying to reference a key that is not a valid identifier, you have to quote it. See the manual for more details.

To select the item under the key 1, you'd do this:

."1"

For your other question on how to obtain the my_name values, you could do this:

to_entries | map(.value.my_name)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.