user1279887
user1279887

Reputation: 518

add value from an object into each element of an array

I have a json object that looks like this:

{
    "data": {
        "id" : 1234,
        "details": [
            {
                "vid": "332",
                "long": -79,
                "lat": 45
            },
            {
                "vid": "33",
                "long": -77,
                "lat": 32
            }
        ]
    }
}

I would like output a csv file from this data that looks like this:

"1234","332","-79", "45"
"1234", "33", "-77", "32"

E.g. I want to add something from a node in each of another node's array's objects, essentially de-normalize the data.

Is there a way to access a value from somewhere else in the json data?

Upvotes: 0

Views: 56

Answers (2)

peak
peak

Reputation: 116967

Or without a variable:

jq -r '.data | [.id] + (.details[] | [.vid, .long, .lat]) | @csv' file.json

If you really want all the values to be quoted, simply add map(tostring) to the pipeline before the final @csv.

Upvotes: 2

choroba
choroba

Reputation: 242168

You can use a variable to do so:

jq '.data.id as $id | .data.details[] | [$id, .vid, .long, .lat]' file.json

Upvotes: 1

Related Questions