I am new to coding in general but I'm trying to shift my attention to learning JAVA, JSON and JQ.
Having said this, I have created the following JSON file:
{
"users":
[
{"Firstname": "Rolo",
"Lastname": "Car",
"Hobbies": ["Metalcore", "concerts", "beach"],
"friends": [
{"Firstname":"Nitsuki",
"Lastname": "Saixx"
},
{"Firstname":"Confesora",
"Lastname": "Kahlan"
}
]
},
{"Firstname":"Ernest",
"Lastname": "Vast"
"Hobbies": ["Barista", "Strategy games", "RPG games"],
"friends": [
{"Firstname":"Diana",
"Lastname": "Vast"
},
{"Firstname":"Pat",
"Lastname": "Vanberg"
}
]
},
{"Firstname":"Juls",
"Lastname": "Santana",
"Hobbies": ["Sew", "Watch Gossip shows", "Foodie"],
"friends": [
{"Firstname":"Laura",
"Lastname": "Reed"
},
{"Firstname":"Sandy",
"Lastname": "Vast"
}
]
}
I am trying to get the following results:
"Rolo"
"Ernest"
"Juls"
When I enter the following JQ command
cat file.json | jq "[].Firstname"
I get the error
jq: error (at <stdin>:56): Cannot index array with string "Firstname"
Any suggestions on what I could be doing wrong? Thank you so much for your time!
CodePudding user response:
.users is an array, so after fixing the obvious errors, you'll find:
jq '.users[].Firstname'
produces the results you expect.
CodePudding user response:
Couple of issues in the json you posted first:
- You need a comma after
"Lastname": "Vast"
- You need to complete the object by closing
users
array (add a]
at the end), and then closing the entire object (adding a}
at the end)
This command then works:
cat test.json | jq '.users[].Firstname'
You need to tell jq which array you want to get the Firstname
values from (the users
array, in your case), as the initial input is an object, and so cannot be traversed via not the collection containing values with a []
Firstname
property.