Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: Zipping two Lists into a List of Objects #623

Closed
timyates opened this issue Nov 20, 2014 · 4 comments
Closed

Question: Zipping two Lists into a List of Objects #623

timyates opened this issue Nov 20, 2014 · 4 comments
Labels

Comments

@timyates
Copy link

Probably a simple question, but given the following JSON:

{
    "columnHeaders": [
        {
            "name": "ga:pagePath",
            "columnType": "DIMENSION",
            "dataType": "STRING"
        },
        {
            "name": "ga:pageviews",
            "columnType": "METRIC",
            "dataType": "INTEGER"
        }
    ],
    "rows": [
        [ "/" , 8 ],
        [ "/a", 4 ],
        [ "/b", 3 ],
        [ "/c", 2 ],
        [ "/d", 1 ]
    ]
}

How can I convert this into a form like:

[
    { "ga:pagePath": "/", "ga:pageviews": 8 },
    { "ga:pagePath": "/a", "ga:pageviews": 4 },
    { "ga:pagePath": "/b", "ga:pageviews": 3 },
    { "ga:pagePath": "/c", "ga:pageviews": 2 },
    { "ga:pagePath": "/d", "ga:pageviews": 1 }
]
@ghost
Copy link

ghost commented Nov 20, 2014

Okay, so first we want to get the columnHeaders as an array of names:

(.columnHeaders | map(.name)) as $headers

Then, for each row, we take the $headers as entries (if this doesn't mean anything to you, refer to the with_entries section of the manual) and we use those to create a new object, in which the keys are the values from the entries and the values are the corresponding values on the row for each of said entries. Tricky, I know.

.rows | map(
    . as $row |
    $headers | with_entries({
        "key": .value,
        "value": $row[.key]
    })
)

Then we put it all together: wrapping it on a filter is left as an exercise for the reader.

jq '(.columnHeaders | map(.name)) as $headers | .rows | map(. as $row | $headers | with_entries({"key": .value, "value": $row[.key]}))' lol.json

@timyates
Copy link
Author

Brilliant! 👍 😄

@ralph-tice
Copy link

I added this to wiki, because I can't get enough of good JQ example usage. https://github.com/stedolan/jq/wiki/jq-Cookbook/ba821a5760a7925e4a52e682e4b0a6248848d732

@ghost
Copy link

ghost commented Nov 20, 2014

That's so cool! I didn't know the wiki had this. I'll have a go at
improving some of the examples!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants