Last active
December 12, 2024 12:57
-
-
Save earthchie/bf6c7dcda912ed7f37c7b61aa84ccaf9 to your computer and use it in GitHub Desktop.
Snippet for parsing the NFT metadata using the Fetch API. Supports both URI and IPFS format.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function parseNFTMetadata(metadata, ipfs_gateway = 'https://ipfs.io/ipfs/'){ | |
const applyIPFSGateway = function(uri){ | |
if(uri instanceof Array){ | |
return uri.map(i=>applyIPFSGateway(i)); | |
}else if(typeof uri === 'object'){ | |
Object.keys(uri).forEach(k=>{ | |
uri[k] = applyIPFSGateway(uri[k]); | |
}); | |
return uri; | |
}else if(typeof uri === 'string'){ | |
return uri.replace('ipfs://', ipfs_gateway); | |
}else{ | |
return uri; | |
} | |
}; | |
try{ | |
const URI = new URL(metadata); // for testing if it error | |
return applyIPFSGateway(await (await fetch(metadata)).json()); | |
}catch(e){ | |
return applyIPFSGateway(metadata); | |
} | |
} |
Create json metadata
function createJSONMetadata(json){
return 'data:application/json,' + encodeURIComponent(JSON.stringify(json))
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: