Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...