JSLT Help: Combine 2 nodes from JSON Input
I'm trying to get a list of all stock items along with their corresponding product details. Can anyone help me with this?
Here’s the sample input I'm working with:
{ "products": [ { "productId": "A1", "price": 10, "category": "Fruit", "brand": "FreshCo" }, { "productId": "B2", "price": 20, "category": "Veg", "brand": "GreenFarm" } ], "stock": [ { "store": { "storeId": "S1" }, "productId": "A1", "available": 5 }, { "store": { "storeId": "S2" }, "productId": "B2", "available": 8 } ] } And here’s the JSLT code I’ve written so far:
let lookupProduct = function(productId) [for (.products) if (.productId == $productId) { "price": .price, "category": .category, "brand": .brand }]
[ for (.stock) let product = lookupProduct(.productId) { "storeId": .store.storeId, "productId": .productId, "available": .available, "price": $product[0].price, "category": $product[0].category, "brand": $product[0].brand } ]
Would appreciate any help. Thanks in advance!
I'm not sure exactly what you want to achieve, but one way to approach this is to first do something like:
let products = { for (.products) .productId : . }
Now you can use get-key($products, "A1") to look up any product you want.
(For later, if you want to create a function, you declare them like this.)
With this in hand your existing top for loop should be pretty easy to adapt.