jq:如何有条件地更改数组值

时间:2019-03-11 23:29:05

标签: json edit jq

json和jq的新功能。我搜索了互联网,但找不到解决我问题的方法。 我有一个json文件,每个对象都包含数组。我需要有条件地更改一些数组元素:如果contact_type = email和诸如“ yahoo.com”之类的值替换为“ yahoo.com”为“ hotmail.com”。 我的档案:

[  
    {
        "name": "fluffy",
        "type": "cat",
        "contact_info": [
             {
                 "contact_type": "phone",
                 "value": "123-456-6789"
             },
             {
                 "contact_type": "email",
                 "value": "fluffy_mean_cat@gmail.com"
             }
        ]
    },
    {
         "name": "breeze",
         "type": "dog",
         "contact_info": [
             {
                  "contact_type": "phone",
                  "value": "125-856-6789"
             },
             {
                  "contact_type": "email",
                  "value": "breeze@yahoo.com"
             }
         ]
    }
]

结果文件必须如下所示:

[
    {
         "name": "fluffy",
         "type": "cat",
         "contact_info": [
             {
                  "contact_type": "phone",
                  "value": "123-456-6789"
             },
             {
                  "contact_type": "email",
                  "value": "fluffy_mean_cat@gmail.com"
             }
         ]
    },
    {
         "name": "breeze",
         "type": "dog",
         "contact_info": [
             {
                  "contact_type": "phone",
                  "value": "125-856-6789"
             },
             {
                  "contact_type": "email",
                  "value": "breeze@hotmail.com"
             }
         ]
    }
]

请帮助。

1 个答案:

答案 0 :(得分:1)

以下是许多可能的解决方案之一:

init<0>()

直接接触

walk( if type == "object"
        and .contact_type == "email"
        and (.value | index("yahoo.com"))
      then .value |= sub("yahoo.com"; "hotmail.com")
      else . end )

def update: if .contact_type == "email" and (.value | index("yahoo.com")) then .value |= sub("yahoo.com"; "hotmail.com") else . end ; map( if .contact_info then .contact_info |= map(update) else . end )

在发布jq 1.6之后,进行了更改,允许删除else .