x3nr0s
x3nr0s

Reputation: 2158

jq - How do I print the entire index of a JSON array in the correct order, instead of printing all of one specific field one after each other?

I have the following JSON:

{
  "family_name": "The Brown Family",
  "members": [
    {
      "name": "James",
      "age": 42
    },  
    {
      "name": "Sarah",
      "age": 43,
    }
  ]
}
{
  "family_name": "The Smith Family",
  "members": [
    {
      "name": "Thomas",
      "age": 32
    },  
    {
      "name": "Jane",
      "age": 30,
    }
  ]
} 

I would like to print the family name of each family, then after this print each index contained in 'members'. I have tried the following in JQ.

echo $myJson | jq -r '"\("Family Name: ") \(.family_name)", "\("Member Name: ") \(.members[].name)", "\("Age: ") \(.members[].age)", "\n"'

My hope was that this would print the following:

Family Name: The Brown Family   
Member Name: James
Age: 42
Member Name: Sarah
Age: 43

Family Name: The Smith Family
Member Name: Thomas
Age: 32
Member Name: Jane
Age: 30

However, instead it prints:

Family Name: The Brown Family   
Member Name: James
Member Name: Sarah
Age: 42
Age: 43

Family Name: The Smith Family
Member Name: Thomas
Member Name: Jane
Age: 32
Age: 30

How do I change my jq script to produce the correct output in the right order? Thanks.

Upvotes: 1

Views: 161

Answers (1)

hek2mgl
hek2mgl

Reputation: 158150

You can use the following command:

jq -r '"Family Name: \(.family_name)",(.members[]|"Member Name: \(.name)","Age: \(.age)")' file.json

Upvotes: 2

Related Questions