1

I am new to Python. Here is my code

class Test(Base):
     __tablename__ = 'test'
     __public__ = ('my_id', 'name')
     my_id = Column(Integer, primary_key=True)
     name = Column(String)
     def __init__(self, id, name):
         self.my_id = id
         self.name = name
     def __repr__(self):
         return "<User('%d','%s')>" % (self.id, self.name)
     @property   
     def json(self):    
         return to_json(self, self.__class__)

output=[]
users= cess.query(Test).order_by(Test.my_id).distinct().all()
for c in users:
    output.append(c.json)

print json.dumps(output)

But this is not correct json? I want to add all the json objects from the for loop into a proper json array, so the client can loop over it ? How can i do this ?

2
  • 1
    I think you should simplify your code in order for us to understand it. Also, that will likely find the source of the error. Commented Oct 1, 2013 at 19:22
  • If you give us an SSCCE, we can run your example and figure out what it's doing wrong. Otherwise, we have to guess what the "this" is and in what way it's not correct JSON (or maybe just not the JSON you expected?) and how the code you haven't shown us might be generating it and so on, which means the odds of us giving you a useful answer are pretty slim. Commented Oct 1, 2013 at 19:48

1 Answer 1

1

You can construct a list of dicts from your query results. Define to_dict method on your model (taken from here):

class Test(Base):
   ...

   def to_dict(self):
       return {c.name: getattr(self, c.name) for c in self.__table__.columns}

Then, make a list of dicts and dump it to json:

users = cess.query(Test).order_by(Test.my_id).distinct().all()
output = [c.to_dict() for c in users]

print json.dumps(output)

Also see:

Sign up to request clarification or add additional context in comments.

3 Comments

@BadLuckBrian could you give an example?
The Test class has only a string and a integer ? What if this has nested classes ? Will the dict function work then as well ?
@BadLuckBrian I'm pretty sure it'll take only table columns into account - it's a pretty straightforward approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.