Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/65886484/using-a-json-key-as-a-lookup-in-jq

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...