I use the following code to sort key/value pairs in JSON files and append them in one file. This works if all keys are in the top level.
from collections import OrderedDict
from textwrap import indent
import json
for i in range(10):
try:
filename = str(i+1)+".json"
def ordered(d, key_order):
return OrderedDict([(key, d[key]) for key in key_order])
desired_key_order = ("name", "description", "image", "attributes")
with open(filename) as file:
d = json.load(file)
result = ordered(d, desired_key_order)
print(json.dumps(result, indent=4))
f = open("collection.json", "a")
f.write(json.dumps(result, indent=4)+","+"\n")
f.close()
except Exception as e:
print('NFT #'+str(i+1), ' is missing from the collection.', "\n")
I want to be able to do the same for files where one of the keys I want to sort among the top level ones is at second level.
I found this solution that I would like to use, but I wasn’t able to integrate it. I get a KeyError
on 'edition'
.
from collections import OrderedDict
from textwrap import indent
import json
for i in range(10):
filename = str(i+1)+".json"
with open(filename) as file:
d = json.load(file)
new_d = {key: d[key] for key in d}
new_d.update(d['edition'])
def ordered(new_d, key_order):
return OrderedDict([(key, new_d[key]) for key in key_order])
desired_key_order = ("edition", "name", "description", "image", "attributes")
result = ordered(new_d, desired_key_order)
print(json.dumps(result, indent=4))
f = open("collection.json", "a")
f.write(json.dumps(result, indent=4)+","+"\n")
f.close()
script and sample data: https://github.com/BarryDB83/pythonscript