I’m trying to grab some key:value pairs from this json file, sorting them and writing them to a new file.
The code below works if I only use top level key:value pairs.
from collections import OrderedDict
import 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("1.json") as json_file:
d = json.load(json_file)
result = ordered(d, desired_key_order)
f = open("new.json", "a")
f.write(json.dumps(result, indent=4))
f.close()
However, I also want to include a second level key:value pair (edition). I know I can define that key I need like this:
edition = d[‘custom_fields’][‘edition’]
But I don’t know how to add it to the top level.
Can anyone explain me how to do it? I’ve uploaded the sample data, including the script that works and the one that doesn’t to this GitHub repo.
Thanks in advance and my apologies if I use wrong terminology, I’m very new to this.
I was able to solve it! Instead of trying to move the key, I created a new one and assigned the value for edition = d[‘custom_fields’][‘edition’] to it. I then rank them the way I did in the first post (replaced d with json_decoded):
import json
from collections import OrderedDict
for i in range(10000):
filename = str(i)+".json"
with open(filename) as json_file:
json_decoded = json.load(json_file)
edition = json_decoded['custom_fields']['edition']
json_decoded.update({"edition":edition})
with open(filename, 'w') as f:
f.write(json.dumps(json_decoded, sort_keys=False, indent=4, separators=(',', ': ')))
def ordered(d, key_order):
return OrderedDict([(key, d[key]) for key in key_order])
desired_key_order = ("edition", "name", "description", "image", "attributes")
with open(filename) as json_file:
d = json.load(json_file)
result = ordered(d, desired_key_order)
f = open("collection.json", "a")
f.write(json.dumps(result, indent=4)+","+"\n")
f.close()