Can I use jq for using parameters from a JSON file to filter and modify another JSON file?

Viewed 125

Let's say I have two input JSON files. The first one is:

[
    {
        "name": "one",
        "keyB": "2",
        "keyC": "3"
    },
    {
        "name": "two",
        "keyB": "15",
        "keyC": "20"
    }
]

And the second one:

{
    "name": "one",
    "type": "FeatureCollection",
    "features": [
        {
            "name": "one",
            "valueA": "0",
            "valueB" : "0"
        },  
        {
            "name": "two",
            "valueA": "11",
            "valueB": "21"
        },
        {
            "name": "one",
            "valueA": "21",
            "valueB": "30"
        },  
        {
            "name": "two",
            "valueA": "1",
            "valueB": "2"
        },
        {
            "name": "one",
            "valueA": "2",
            "valueB": "3"
        },  
        {
            "name": "two",
            "valueA": "5",
            "valueB": "3"
        }
    ]
}

I'd like to create a logic that when .[].name from the first file is equals to .features[].name from the second file I concatenate its corresponding keys from the first file on the second file (considering that the value of .[].name on the first file is always unique). So the result would be the following:

{
    "name": "one",
    "type": "FeatureCollection",
    "features": [
        {
            "name": "one",
            "valueA": "0",
            "valueB" : "0",
            "keyB": "2",
            "keyC": "3"
        },  
        {
            "name": "two",
            "valueA": "11",
            "valueB": "21",
            "keyB": "15",
            "keyC": "20"
        },
        {
            "name": "one",
            "valueA": "21",
            "valueB": "30",
            "keyB": "2",
            "keyC": "3"
        },  
        {
            "name": "two",
            "valueA": "1",
            "valueB": "2",
            "keyB": "15",
            "keyC": "20"
        },
        {
            "name": "one",
            "valueA": "2",
            "valueB": "3",
            "keyB": "2",
            "keyC": "3"
        },  
        {
            "name": "two",
            "valueA": "5",
            "valueB": "3",
            "keyB": "15",
            "keyC": "20"
        }
    ]
}

In this output, I just checked where the name is equal on both JSON files and then I brought the keys keyB: "2", "keyC": "3" where name == "one" and keyB: "15", "keyC": "20" where name == "two". Is it possible to do with jq? Can I work with two JSON files in a way that I get parameters from one file to give it to another one?

1 Answers

Yeah, just save the first one in a variable.

INDEX(.name) as $p | inputs | .features |= map($p[.name] + .)

Online demo

Related