Update NFT JSON Metadata with Python

TechJD
2 min readMay 16, 2022

--

If you have ever tried to deploy a huge NFT project, you’ve come to realize the importance of having a reliable script to update the metadata, especially since your metadata will not be complete until you have committed the image folder to IPFS and retrieved the hash for the base URI. But what about when you want to change the metadata: perhaps add new categories or delete old ones? I’ve got a simple script that only requires Python.

import os

In your .py file, all you need is to import os.

files = os.listdir('/Users/your/file/location')

The ‘listdir’ function creates an array. So now, we just need to traverse the array with a for loop.

for x in files:
with open('/Users/your/file/location/'+x, 'rb') as file :
filedata = file.read()

‘rb’ stands for ‘read bytes,’ which is necessary in order to read lines in a JSON file.

# Replace the target string
filedata = filedata.replace(bytes('REPLACE-THIS-WITH-YOUR-URL', encoding='utf-8'), bytes('ipfs://YOUR_IPFS_HASH', encoding='utf-8'))

Python has a built-in replace function, where the first parameter is the input to be searched for and replaced by the second input. You need to convert the string to bytes and specify the encoding.

with open('/Users/your/file/location/'+x, 'wb') as file:
file.write(filedata)

Open the file again and write the changes to it.

Full code:

import osfiles = os.listdir('/Users/your/file/location')
for x in files:
with open('/Users/your/file/location/'+x, 'rb') as file :
filedata = file.read()

# Replace the target string
filedata = filedata.replace(bytes('REPLACE-THIS-WITH-YOUR-URL', encoding='utf-8'), bytes('ipfs://YOUR_IPFS_HASH', encoding='utf-8'))

# Write the file out again
with open('/Users/your/file/location/'+x, 'wb') as file:
file.write(filedata)

You can replace whichever criteria you want.

--

--

TechJD
TechJD

Written by TechJD

Law, programming, and everything in-between! Coming up with fun coding projects with real-world application.