我有这样的JSON:
{
"photo_807": "Ih2RnaBTg2o.jpg",
"photo_604": "zodCm9fQgX8.jpg",
"photo_130": "4Dx-SUNKBw4.jpg",
"photo_75": "7COWb8ou1qA.jpg",
"user_id": 100,
"owner_id": -2435432542783750,
"access_key": "fc5275423676514042234324265cc3df7607c",
"post_id": 380435645368865101,
"date": 14858616848616779856424245814,
"text": "",
"height": 417,
"width": 740,
"id": 45624575446886886564368555,
"album_id": -36
}
我想从输出中得到唯一的Photo值,我想得到这个:
"photo_807": "Ih2RnaBTg2o.jpg"
"photo_604": "zodCm9fQgX8.jpg"
"photo_130": "4Dx-SUNKBw4.jpg"
现在关于我的问题,从下一个JSON文件我将获得具有如下新名称的照片项目:
"photo_181": "Ih2RnaBTg2o.jpg",
"photo_583": "zodCm9fQgX8.jpg",
"photo_975": "4Dx-SUNKBw4.jpg",
"photo_32": "7COWb8ou1qA.jpg",
如何从动态项目中获取此值photo_ *?
我尝试这样的事情:
cat ./json3.txt | jq '.response.items[].attachments[].photo | select(.photo | startswith("photo"))'
但它不起作用。
当我跑步时:
cat ./json3.txt | jq '.response.items[].attachments[].photo'
我得到了所有项目的输出:
{
"photo_807": "Ih2RnaBTg2o.jpg",
"photo_604": "zodCm9fQgX8.jpg",
"photo_130": "4Dx-SUNKBw4.jpg",
"photo_75": "7COWb8ou1qA.jpg",
"user_id": 100,
"owner_id": -2435432542783750,
"access_key": "fc5275423676514042234324265cc3df7607c",
"post_id": 380435645368865101,
"date": 14858616848616779856424245814,
"text": "",
"height": 417,
"width": 740,
"id": 45624575446886886564368555,
"album_id": -36
}
有人可以帮助我吗?
提前致谢!
答案 0 :(得分:2)
您可以在jq-play上使用jq
过滤器,如下所示!
jq '. | to_entries[] | select(.key | startswith("photo")) | "\(.key) :\(.value)"' json
"photo_807 :Ih2RnaBTg2o.jpg"
"photo_604 :zodCm9fQgX8.jpg"
"photo_130 :4Dx-SUNKBw4.jpg"
"photo_75 :7COWb8ou1qA.jpg"
我们的想法是使用内置的to_entries[],它会将您的输入转换为键值对,如下所示。请参阅下面仅使用to_entries[]
jq '. | to_entries[]' json
{
"key": "photo_807",
"value": "Ih2RnaBTg2o.jpg"
}
{
"key": "photo_604",
"value": "zodCm9fQgX8.jpg"
}
{
"key": "photo_130",
"value": "4Dx-SUNKBw4.jpg"
}
{
"key": "photo_75",
"value": "7COWb8ou1qA.jpg"
}
{
"key": "user_id",
"value": 100
}
{
"key": "owner_id",
"value": -2435432542783750
}
{
"key": "access_key",
"value": "fc5275423676514042234324265cc3df7607c"
}
{
"key": "post_id",
"value": 380435645368865100
}
{
"key": "date",
"value": 14858616848616779000000000000
}
{
"key": "text",
"value": ""
}
{
"key": "height",
"value": 417
}
{
"key": "width",
"value": 740
}
{
"key": "id",
"value": 45624575446886885000000000
}
{
"key": "album_id",
"value": -36
}
在此输出中,我们使用内置startswith()过滤.key
值,该值以字符串photo
开头,并打印.key
匹配对象的{1}}和.value
对。