Skip to content

Instantly share code, notes, and snippets.

@jcurbelo
Last active February 21, 2023 23:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jcurbelo/f683c7434693c3c7b4c0e3a532e10bf4 to your computer and use it in GitHub Desktop.
Save jcurbelo/f683c7434693c3c7b4c0e3a532e10bf4 to your computer and use it in GitHub Desktop.
Merge several metadata JSON files into one
import json
import os
FOLDER = './metadata'
result = []
# read all .json files in the folder
print('Reading files...')
json_files = [f for f in os.listdir(FOLDER) if f.endswith('.json')]
print('Found {} files.'.format(len(json_files)))
print('Merging...')
# sorts the files by their number
json_files.sort(key=lambda x: int(x.split('.')[0]))
for idx, f in enumerate(json_files):
with open(os.path.join(FOLDER, f)) as json_file:
data = json.load(json_file)
# sets a dummy image field
data['image'] = 'ipfs://YOUR_CID/' + str(idx + 1) + '.png';
result.append(data)
print('Writing output...')
# writes the result to a new file
with open('metadata.json', 'w') as outfile:
json.dump(result, outfile)
print('Done.')
@jcurbelo
Copy link
Author

How to use this script

  1. Download this merge.py script and save it at the same level as your metadata JSON folder:

Screen Shot 2022-05-13 at 12 43 30 PM

  1. Open up a terminal at the same folder level and run the following command:
python merge.py

Screen Shot 2022-05-13 at 12 46 31 PM

@michaeljcoyne
Copy link

File "merge.py", line 19
data['image'] = f'ipfs://YOUR_CID/{idx + 1}.png'

@michaeljcoyne
Copy link

michaeljcoyne commented Jun 16, 2022

@jcurbelo
Copy link
Author

jcurbelo commented Aug 2, 2022

@michaeljcoyne thank you so much for noticing this! you are right, this interpolation syntax was added in python 3.6 see this SO answer. Updated my gist thanks to you! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment