Skip to content

Instantly share code, notes, and snippets.

@femmerling
Created October 11, 2013 12:05
Show Gist options
  • Save femmerling/6933574 to your computer and use it in GitHub Desktop.
Save femmerling/6933574 to your computer and use it in GitHub Desktop.
Function to simplify json parsing for SQLAlchemy model creation
"""
I know that parsing json values for SQLAlchemy models is a pain in the ass.
The following two helpers will get you cleaner code and handles the json while converting it into code.
This is commonly use in Flask-SQLAlchemy applications. My latest backyard release already included these functions
"""
import json
# this import is just an example of an SQLAlchemy module, it can be any model that you wish to use
from app.models import User
def new_parser(passed_object, payload_data):
payload = json.loads(payload_data)
for key, value in payload.items():
if hasattr(passed_object, key):
setattr(passed_object, key, value)
return passed_object
def edit_parser(passed_object, payload_data):
payload = json.loads(payload_data)
for key, value in payload.items():
if key != "id" and value != None:
if hasattr(passed_object, key):
setattr(passed_object, key, value)
return passed_object
# try it out!!!
user_dictionary = {"user_name":"johndoe","first_name":"john","last_name":"doe"}
user_json = json.dumps(user_dictionary)
# creating new user
new_user = User()
new_user = new_parser(new_user, user_json)
# then you can save the object into your database
# edit a new user
id = 2
existing_user = User.query.get(2)
existing_user = edit_parser(existing_user, user_json)
# then you can save the edited object into your database
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment