在bash中使用jq更改json [英] changing the json using jq in bash

查看:580
本文介绍了在bash中使用jq更改json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下json

{
    "name" : "qwerty",
    "values" :[
    {
        "field1" : [
            "val1"
            ],
        "field2" : [
            "val2"
            ],
        "name1" : [["a", "b"], ["c", "d"]]
    },
    {
        "field1" : [
            "val3"
            ],
        "field2" : [
            "val4"
            ],
        "name1" : [["a", "b"], ["c", "d"]]
    },
    {
        "field1" : [
            "val5"
            ],
        "field2" : [
            "val6"
            ],
         "name1" : [["a", "b"], ["c", "d"]]
    }
    ]
}

我需要在bash中使用jq将上述json更改为以下

I need to change the above json to the following using jq in bash

{
    "name" : "qwerty",
    "values" :[
    {
        "field1" :  "val1",
        "field2" :  "val2",
        "new_name" : [["a", "b"], ["c", "d"]]
    },
    {
        "field1" : "val3",
        "field2" : "val4",
        "new_name" : [["a", "b"], ["c", "d"]]
    },
    {
        "field1" : "val5",
        "field2" : "val6",
        "new_name" : [["a", "b"], ["c", "d"]]
    }
    ]

}

在这里,我面临以下问题:

Here i am facing the following issues :

我尝试用标签值解析内部json,并用空格替换'['']',但是,当我尝试将"values"放入列表形式的变量中时,jq会美化并显示每个新行都作为数组的元素.

I tried parsing the inner json with tag values and replace the '[' ']' with spaces, however, when i try to put the "values" in a variable in the form of list, jq is prettifying and then showing each new line as a element of an array.

values数组中内部json的数量不固定.

The number of inner jsons in the values array is not fixed.

有人可以帮我构筑要在bash中运行的jq语句,以进行所需的更改吗.

Can some one please help me with framing the jq statement to be run in bash to make the required changes.

推荐答案

这应该有效;我不确定是否有方法可以重构对field1field2的分配:

This should work; I'm not sure if there is a way to refactor the assignments to field1 and field2:

jq '.values[] |= (.field1=.field1[0] | .field2=.field2[0])' tmp1.json

这篇关于在bash中使用jq更改json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆