Search code examples
ethereumsolidityipfsjs-ipfs

How to convert IPFS link into JSON?


So my friends are making an NFT contract and using IPFS to store the metadata. I want to look at the JSON contained in that IPFS link generated so that I can display the metadata in a Bootstrap card. When I use this code to call one of the surfaced contract functions:

const tokenContract = new ethers.Contract(nftaddress, NFT.abi, provider);
const nft = await tokenContract.tokenURI(1);
console.log("nft:", nft);

I get this output, so I can see the function call from the contract worked:

nft: ipfs://Qmchgm5...GLnGMk

But then when I try to turn that IPFS link into a JSON format (as I can see when I visit the link URL) this doesn't work and throws this error:

console.log('nft:', nft.json());
// TypeError: nft.json is not a function

Can someone explain why putting in the link into my browser can show the JSON, but trying to read it from the link cannot? I assume this is some basic functionality of IPFS, but I cannot find anything (that makes sense to me, total newbie) telling me about this functionality and how to READ an IPFS object in my code.

Thank you in advance! -PhilosophOtter


Solution

  • The IPDS CID is not an object but a reference to an asset stored on the IPFS network so for example if the IPFS hash was: bafybeidyp5tc6vfjsis7rziok4o6j6ckjajpug4wceavcyujm6bsiqqk4m You can access it using an IPFS gateway like Dweb so you can do something like this: https://bafybeidyp5tc6vfjsis7rziok4o6j6ckjajpug4wceavcyujm6bsiqqk4m.ipfs.dweb.link/ So you can get the JSON like this:

    const data = await fetch("https://bafybeidyp5tc6vfjsis7rziok4o6j6ckjajpug4wceavcyujm6bsiqqk4m.ipfs.dweb.link/")
    const json = await data.json()
    console.log(json)
    

    You should also read this