I parse a json file with jq:
jq .response[1].text file.json
It works fine, but each time I have to enter the number .response[2].text, .response[3].text etc. I want to get all the values at once (200 values)
But when I do:
jq .response[].text file.json
It gives an error: Cannot index number with string "text"
The file looks like this:
{
"response": [
1000,
{
"id": ,
"date": ,
"owner_id": ,
"from_id": ,
"post_type": "post",
"text": "blabla",
"attachment": {
"type": "photo",
"photo": {
"pid": ,
"aid": -7,
"owner_id":
}
},
"attachments": [
{
"type": "photo",
"photo": {
}
},
{
"type": "link",
"link": {
"url": "",
"title": "",
"description": "",
"target": "external"
}
}
],
"post_source": {
"type": "vk"
},
"comments": {
"count": 0,
"groups_can_post": true,
"can_post": 1
},
},
{
"id": ,
"date": ,
"owner_id": ,
"from_id": ,
"post_type": "post",
"text": "blabla",
"attachment": {
"type": "link",
"link": {
"url": "",
"title": "",
"description": "",
"target": "external",
"
}
Evidently one of the items in the array is a string. If your jq supports "?", then one possibility would be to use it:
.response[].text?
Another would be to check the type explicitly, e.g.:
.response[] | objects | .text
Yet another possibility:
.response[] | select(type=="object" and has("text")) | .text
If you want to have a placeholder value when there is no "text" field:
.response[] | if type=="object" and has("text") then .text else null end
So it really depends on your requirements and perhaps the version of jq that you are using.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With