I have a JSONB data stored in a column called data
in table nftdata
. Inside this JSON data (as shown below) there is a JSON array at result.data.items
. This is an array of 2400 JSON objects but I have shown two here as an example:
{
"api_version": "0.1",
"result": {
"api_code": 200,
"api_response": "Success",
"data": {
"collection": "XXX NFT",
"ranking_url": "https://nft",
"twitter": "https://twitter.com/nft/",
"discord": "https://discord.com/invite/",
"website": "https://nft.io/",
"description": "2",
"logo": "https://icons/f245c3aea5e279691f5f460d9d499afe.jpg",
"items": [
{
"id": 2414,
"link": "/2414",
"mint": "FHAJS21yJBtYDuix1x7woZPUo",
"name": "NFT #2414",
"description": "-",
"image": "https://arweave.net/mKbawCJP4dX9_IZg",
"attributes": ["Deleted to shorten post"],
"rank": 1,
"rank_algo": "h",
"all_ranks": {
"is": 1,
"trait_normalized": 1,
"statistical_rarity": 1876
}
},
{
"id": 198,
"link": "/198",
"mint": "EiGbBm7CsB8ZeZF5Hg",
"name": "NFT #198",
"description": "-",
"image": "https://arweave.net/fAVzxoqcsracjf",
"attributes": ["Deleted to shorten post"],
"rank": 2,
"rank_algo": "h",
"all_ranks": {
"is": 2,
"trait_normalized": 2,
"statistical_rarity": 2246
}
}
]
}
}
}
The table this data is in is held like this:
collection_ID (text) | data (jsonb) |
---|---|
collection1 | JSONB data blob (as above) |
collection2 | JSONB data blob (as above) |
I would like to use a Postgres query to first find the right table row based on its primary key (e.g. collection1
), then search through the JSON in the data column of that particular table row for one of the 2400 objects (stored at result.data.items
) with a particular ID (in nodejs it would be something like result.data.items[i].id
) and if found, return the particular 'items' object (e.g. result.data.items[i]
).
For example, I would like to search collection1
for id 2414
and return:
{
"id": 2414,
"link": "/2414",
"mint": "FHAJS21yJBtYDuix1x7woZPUo",
"name": "NFT #2414",
"description": "-",
"image": "https://arweave.net/mKbawCJP4dX9_IZg",
"attributes": [ 'Deleted to shorten post'
],
"rank": 1,
"rank_algo": "h",
"all_ranks": {
"is": 1,
"trait_normalized": 1,
"statistical_rarity": 1876
}
}
Edit: thanks for the answer below which solved the problem. For future readers I implemented the query in nodejs like this:
//pass nftid as string and collectionstring (collection_ID) as string into function
var querystring = "SELECT jsonb_path_query_first(data #> '{result,data,items}', '$[*] ? (@.id == " + nftid + " || @.id == \"" + nftid + "\")') AS result FROM howraredata WHERE collection_id = '" + collectionstring + "' "
pgclient.query(querystring, (err, res) => {
if (err) throw err
//do stuff
})