spetty flakson spetty flakson - 5 months ago 32
JSON Question

how to make SQLAlchemy to_json function that doesnt add column type to ouput?

I have an association object that accesses two fields in its to_json function. One is a string and one is a decimal number

here is the object:

class DrinkIngredient(db.Model):
__tablename__ = 'drink_ingredient'
drink_id = db.Column(db.Integer, db.ForeignKey("drink.id"), primary_key=True)
ingredient_id = db.Column(db.Integer, db.ForeignKey("ingredient.id"), primary_key=True)
units = db.Column(db.Numeric(4, 2)) # Total of 4 digits, 2 after decimal: 00.00

ingredient = db.relationship("Ingredient")

def __init__(self, ingredient=None, units=None):
self.ingredient = ingredient
self.units = units

def __repr__(self):
return '<DrinkIngredient %g units of %r>' % (self.units, self.ingredient)

def to_json(self):
json_drinkIngredient = {
"ingredient": self.ingredient.name,
"amount": self.units
}
return json_drinkIngredient


Ingredient.name is a string in another table called
Ingredient
.

When i call this function I get an output like this
{'amount': Decimal('0.20'), 'ingredient': u'grenadine'}


why is the
Decimal('...')
and
u'...'
being included and how do i correctly make these json objects without the type listed.

Also this isn't a huge concern but i'd rather them be in the reverse order as that is the order i defined them in and I'm not sure why they aren't in that order.

Answer

Use the json module to output proper json.

from simplejson import dumps

def to_json(self):
    json_drinkIngredient = dumps({
        "ingredient": self.ingredient.name,
        "amount": self.units
    })
    return json_drinkIngredient

About your second question, the reason is that python dictionaries are unordered. If it's important to maintain the order with which you declared the keys use an OrderedDict and pass that object to json.dumps:

from collections import OrderedDict

d=OrderedDict()
d['ingredient']=self.ingredient.name
d['amount']=self.units