Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.