如何使用Grep从JSON中节省价值

时间:2018-05-14 17:47:56

标签: json regex grep

我只是想知道如何只保存is_verified:true值“Usernames”。

{
    "users": [{
        "pk": 29394004,
        "username": "chrisbrownofficial",
        "full_name": "Kid INDIGO",
        "is_private": false,
        "is_verified": true,
        "profile_pic_url": "https://instagram.fkwi3-1.fna.fbcdn.net/vp/ef4cc2c1ff4f38a06b852b37fe63f82a/5B8BECFB/t51.2885-19/s150x150/30590388_378690675946907_2025648692966457344_n.jpg",
        "profile_pic_id": "1758771593280949227_29394004",
        "chaining_info": {
            "sources": "[3, 4, 7, 8]"
        },
        "profile_chaining_secondary_label": "Kid INDIGO"
    }, {
        "pk": 17978002,
        "username": "djkhaled",
        "full_name": "DJ KHALED",
        "is_private": false,
        "is_verified": false,
        "profile_pic_url": "https://instagram.fkwi3-1.fna.fbcdn.net/vp/eb6324512b5c034a194acb6bc7bf21de/5B7EBF5A/t51.2885-19/s150x150/28155457_527972687583107_7503145280125009920_n.jpg",
        "profile_pic_id": "1726285422685771850_17978002",
        "chaining_info": {
            "sources": "[2, 3, 4, 7, 8]"
        },
        "profile_chaining_secondary_label": "DJ KHALED"
    }, {
        "pk": 6720655,
        "username": "meekmill",
        "full_name": "Meek Mill",
        "is_private": false,
        "is_verified": true,
        "profile_pic_url": "https://instagram.fkwi3-1.fna.fbcdn.net/vp/0b7220ebde06e977de982518e5e7103b/5B9402A0/t51.2885-19/s150x150/19986196_677620155771292_1453652395958468608_a.jpg",
        "profile_pic_id": "1556078075425574845_6720655",
        "chaining_info": {
            "sources": "[2, 3, 4, 7, 8]"
        },
        "profile_chaining_secondary_label": "Meek Mill"
    }, {

示例,因为他们获得了“is_verified”而保存在下面:true, 所以要保存“is_verified”的用户名:true。

chrisbrownofficial
meekmill

尝试:grep -Po'“is_verified”:true'

但尝试失败。

我希望有人可以帮助我。

2 个答案:

答案 0 :(得分:0)

如果要给出所有属性的值,那么

cat grep2 | grep '"is_verified": true' -B3 | grep '"username":' | sed 's/ *"username": "\(.*\)",/\1/'

首先grep用于查找is_verified值为true的条目。 -B3选项也会在匹配行上方打印3行。每个is_verified上方的第三行是username字段。

第二个grep获取所有username字段,然后使用sed提取用户名。

输出是:

chrisbrownofficial
meekmill

答案 1 :(得分:0)

这段代码可能会对您有所帮助:

 echo $(cat yourJsonFilePath) | tr "," "\n" | grep '"is_verified": true' -B3 | grep '"username"' | sed -r 's/"username"://' | sed -e 's/"\(.*\)"/\1/'

我们的想法是更换每个"," by" \ n"。然后,grep is_verified行并检索上面的3行。运行此代码,结果将是:

 chrisbrownofficial
 meekmill