Wolf Wolf - 12 days ago 6
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)


activejson
isn't pulling the template
j
fresh through each iteration of the loop. (I'm able to pull old, modified values from previous iterations in
activejson
in the "modify properties here" area.) My understanding is that
activejson
points to
j
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?

Answer

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

activejson = copy.deepcopy(j)
Comments