Skip to content

Instantly share code, notes, and snippets.

@MattMS
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattMS/9505339 to your computer and use it in GitHub Desktop.
Save MattMS/9505339 to your computer and use it in GitHub Desktop.
Django fixtures from JSON
"""
Simple operations for editing JSON Django fixtures.
These functions may be useful as example code for manipulating a JSON
file so it plays nice as a Django fixture.
"""
import json
def add_pk_to_list():
"""
Add pk integer to each object.
"""
with open('items.json') as f:
data = json.load(f)
i = 0
for ob in data:
ob['pk'] = i
i += 1
with open('fixture.json', 'w') as f:
json.dump(data, f)
def move_attr_to_field(field_name):
"""
Move object attribute to fields object.
"""
with open('fixture.json') as f:
data = json.load(f)
for model in data:
fields = model.get('fields', {})
try:
fields[field_name] = model.pop(field_name)
except KeyError:
pass
model['fields'] = fields
with open('fixture2.json', 'w') as f:
json.dump(data, f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment