Wolf Wolf - 1 month ago 14
JSON Question

JSON as template: does not clear

I'm importing a JSON file and using it as a template over which I modify some of the properties.

with open('example.json') as data_file:
j = json.load(data_file)
... # and within a loop:
with open('output.json', 'w') as outfile:
activejson = j # I would like this to reset or pull fresh from j
... # modify properties here
json.dump(activejson, outfile, indent=4)

isn't pulling the template
fresh through each iteration of the loop. (I'm able to pull old, modified values from previous iterations in
in the "modify properties here" area.) My understanding is that
points to
rather than serving as a copy but
activejson = j.copy()
doesn't appear to do the trick either, nor does
activejson = {}
. What is the correct command/way to empty this variable and pull the template fresh after each iteration? What is the most efficient way to handle this?


Since JSON is usually structured as nested objects, you would need to use copy.deepcopy.

activejson = copy.deepcopy(j)