Trouble retrieving NFT image data from nested API response

I’m working on an app that lets users search for NFTs using the Moralis API. The problem is I can’t figure out how to get the image URL from the API response. Here’s what I’ve got so far:

const fetchNFTData = async (searchTerm) => {
  const apiKey = 'YOUR_API_KEY_HERE';
  const url = `https://api.example.com/v1/nfts/search?q=${searchTerm}&limit=10`;
  
  const response = await fetch(url, {
    headers: { 'X-API-Key': apiKey }
  });
  
  const data = await response.json();
  setNFTResults(data.items);
};

// Later in the component
{nftResults.map((nft, index) => (
  <div key={index}>
    <p>{nft.tokenId}</p>
    {/* How do I display the image here? */}
  </div>
))}

The API returns a metadata field that looks like this:

{"name":"Cool NFT","image":"https://example.com/nft.jpg"}

How can I extract and use the image URL from this metadata? I’ve tried various ways but nothing seems to work. Any help would be great!

yo flyingeagle, ive had this issue b4. try console.logging data.items[0] to see the exact structure. if metadata is a string, u gotta JSON.parse(nft.metadata) first. then u can grab the image url like metadata.image. hope that helps bro! let us know if u get it workin

hey there FlyingEagle! i’ve been playing around with NFT stuff too and ran into similar headaches. have you tried logging the whole response to see exactly what you’re getting back? sometimes these APIs can be tricky with how they nest things.

also, just curious - what kind of NFTs are you working with? anything cool? :smile:

btw, if the metadata is coming back as a string like you showed, you might need to parse it first. maybe try something like:

const metadata = JSON.parse(nft.metadata);
<img src={metadata.image} alt={metadata.name} />

let me know if that helps or if you’re still stuck! always fun to chat about NFT projects :raised_hands:

I’ve dealt with similar issues when working with NFT APIs. The metadata field you’re getting is likely a string containing JSON, not a parsed object. To access the image URL, you’ll need to parse this metadata string first.

Try modifying your code like this:

{nftResults.map((nft, index) => {
  const metadata = JSON.parse(nft.metadata);
  return (
    <div key={index}>
      <p>{nft.tokenId}</p>
      <img src={metadata.image} alt={metadata.name} />
    </div>
  );
})}

This should parse the metadata string into an object, allowing you to access the ‘image’ property. If you’re still having trouble, double-check the API documentation to ensure you’re accessing the metadata field correctly. Some APIs might nest it differently or use a different field name.