How to read data from IPFS

Viewed 3999

I uploaded a JSON file to IPFS using Pinata.

Link:

https://gateway.pinata.cloud/ipfs/QmXjUdgnkLLKi3fvZjvnyVUQv4kHpgobjPo67FpyqXxPhe

JSON File:

{
"attributes" : [ {
  "trait_type" : "Breed",
  "value" : "Maltipoo"
}, {
  "trait_type" : "Eye color",
  "value" : "Mocha"
} ],
"description" : "Colorful pots",
"image" : "https://gateway.pinata.cloud/ipfs/QmTgqf6NY2BtsB24aU6vVmuEBunztua5vxwcCRBqwGjHLm",
"name" : "Pots"
}

When I call the contract I get back the URL. How can I access the key "image" when using the following code?

async function showNFT() {

try {

  const nft = await nftContract.methods.tokenURI("1").call()
  console.log(nft)
  // https://gateway.pinata.cloud/ipfs/QmXjUdgnkLLKi3fvZjvnyVUQv4kHpgobjPo67FpyqXxPhe

} catch (err) {
   console.log('Error:' + err);
}

}

Thank you so much

1 Answers

I found a solution to access the JSON data, by using fetch() and json().

const nft = await nftContract.methods.tokenURI("1").call()
const response = await fetch(nft);

if(!response.ok)
  throw new Error(response.statusText);

const json = await response.json();
console.log(json.image) 
Related