Skip to content

Instantly share code, notes, and snippets.

@earthchie
Last active December 12, 2024 12:57
Show Gist options
  • Save earthchie/bf6c7dcda912ed7f37c7b61aa84ccaf9 to your computer and use it in GitHub Desktop.
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.
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);
}
}
@earthchie
Copy link
Author

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