Search code examples
jsonconcatenationjq

jq : combine two files and add as new element


I'm new to jq and tried to search the solution of my issue, which is the following: I have two files config.json and types.json. And I want to append the types.json to config.json on the root level, and name it as a new element, i.e. "typelist" How to do it with jq ?

config.json:

{
    "origconfig1": {
        "id1Config1": null,
        "id2Config1": true,
        "id3Config1": false,
        "id24Config1": false
    },
    "origconfig2": {
        "id1Config2": "",
        "id2Config2": "3a4b68",
        "id3Config2": "f2af35",
        "id4Config2": true,
        "id5Config2": "d.m.Y",
        "id6Config2": true
    }
}

and types.json:

[{
       "code": "CODE_TYPE1",
       "languageCode": "EN",
       "type": "TYPE1"
    }, {
       "code": "CODE_TYPE2",
       "languageCode": "EN",
       "type": "TYPE2"
    }, {
       "code": "CODE_TYPE3",
       "languageCode": "EN",
       "type": "TYPE3"
    }
]

The target is to have an out.json file like the following:

{
    "origconfig1": {
        "id1Config1": null,
        "id24Config1": false,
        "id2Config1": true,
        "id3Config1": false
    },
    "origconfig2": {
        "id1Config2": "",
        "id2Config2": "3a4b68",
        "id3Config2": "f2af35",
        "id4Config2": true,
        "id5Config2": "d.m.Y",
        "id6Config2": true
    },
    "typelist": [ /*This should be added*/
        {
            "code": "CODE_TYPE1",
            "languageCode": "EN",
            "type": "TYPE1"
        },
        {
            "code": "CODE_TYPE2",
            "languageCode": "EN",
            "type": "TYPE2"
        },
        {
            "code": "CODE_TYPE3",
            "languageCode": "EN",
            "type": "TYPE3"
        }
    ]
}

I tried also with

jq --jsonargs types types.json '. * .[\"typelist\"].$types' config.json > out.json

but I get the following error:

jq: error: types/0 is not defined at , line 1:


Solution

  • You're looking for something like this:

    jq '.typelist = input' config.json types.json