AndyK
AndyK

Reputation: 13

Using a JSON key as a lookup in JQ

I have some JSON that looks like this:

{
    "itmVarModel": {
        "menuItemMap": {
            "0": {
                "matchingVariationIds": [1234],
                "displayName": "4 GB"
            },
            "1": {
                "matchingVariationIds": [5678],
                "displayName": "16 GB"
            }
        },
        "itemVariationsMap": {
            "5678": {
                "price": "GBP 62.99",
                "variationId": 5678
            },
            "1234": {
                "price": "GBP 15.00",
                "variationId": 1234
            }
        }
    }
}

I need to extract the name and price so that it looks like this:

{
  "itemname": "16 GB",
  "itemprice": "GBP 62.99"
}
{
  "itemname": "4 GB",
  "itemprice": "GBP 15.00"
}

I've just come across JQ which looks perfect for the job but the nearest I have got is:

[.itmVarModel.menuItemMap[].matchingVariationIds[]] as $names | {itemname: .itmVarModel.menuItemMap[].displayName, itemprice: .itmVarModel.itemVariationsMap."$names".price}

I am struggling with the syntax and don't really know what I am doing tbh.

Upvotes: 1

Views: 102

Answers (1)

oguz ismail
oguz ismail

Reputation: 50750

The easiest way to achieve this would be to keep itemVariationsMap in a variable, and retrieve item prices from there; not the other way around.

.itmVarModel
| .itemVariationsMap as $m
| .menuItemMap[]
| { itemname: .displayName, itemprice: $m["\(.matchingVariationIds[0])"].price }

Online demo

Upvotes: 1

Related Questions