12

I'm trying to print only certain values from a json (one line per sub-object) repeating one value from the top object on each line.

Sample input:

[
    {
        "name": "level1Name",
        "lv1id": "id1",
        "requests": [
            {
                "lv2id": "id2",
                "name": "lvl2requestA",
                "startDate": "2019-02-05 08:52:33.663+0000",
                "requestState": "Succeeded"
            },
            {
                "lv2id": "id2",
                "name": "lvl2requestB",
                "startDate": "2019-02-05 08:52:33.421+0000",
                "requestState": "Succeeded"
            }
        ]
    },
    {
        "name": "level1Name",
        "lv1id": "id12",
        "requests": [
            {
                "lv2id": "id2",
                "name": "lvl2requestD",
                "startDate": "2019-02-05 08:52:19.823+0000",
                "requestState": "Succeeded"
            },
            {
                "lv2id": "id2",
                "name": "lvl2requestA",
                "startDate": "2019-02-05 08:52:19.689+0000",
                "requestState": "Succeeded"
            }
        ]
    }
]

Targeted Output

["id1","2019-02-05 08:52:33.663+0000","lvl2requestA","Succeeded"]
["id1","2019-02-05 08:52:33.421+0000","lvl2requestB","Succeeded"]
["id12","2019-02-05 08:52:19.823+0000","lvl2requestD","Succeeded"]
["id12","2019-02-05 08:52:19.689+0000","lvl2requestA","Succeeded"]

I've tried several attempts (e.g. using Variable / Symbolic Binding Operator). Any clue is welcomed.

1 Answer 1

15
$ jq -c '.[] | .lv1id as $id | .requests[] | [$id, .startDate, .name, .requestState]' file.json
["id1","2019-02-05 08:52:33.663+0000","lvl2requestA","Succeeded"]
["id1","2019-02-05 08:52:33.421+0000","lvl2requestB","Succeeded"]
["id12","2019-02-05 08:52:19.823+0000","lvl2requestD","Succeeded"]
["id12","2019-02-05 08:52:19.689+0000","lvl2requestA","Succeeded"]

This takes each of the elements of the top-most array (.[]) and assigns the element's .lv1id to $id. It then iterates over the .requests[] array of that element and constructs the output array for each of its elements consisting of the various bit that you seem to require, including $id remembered from earlier.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .