0

I have this class in python:

class Defendant(db.Model, DictSerializable):
    id = db.Column(db.Integer, primary_key=True)
    Name_Full = db.Column(db.Text, index=True)

I'm using SqlAlchemy to query the database to get results back. It's working fine, I can push them out to the screen without issues iterating through one by one.

Now I need to get them into a json array so I can do some cool grid stuff. Here's what I'm trying:

Defendants = models.Defendant.query.limit(50).all()
defendantList = ""
for d in Defendants:
    defendantList += "{Name_Full : " + d.Name_Full + "}"

I've tried various things like jsonify(Defendants), etc, but I'm missing something. I get errors with dict or serializeable or iterable.

This seems like a pretty simple thing to do, and I hope I'm just missing something. Thanks in advance!

oppassum
  • 1,746
  • 13
  • 22
  • `"{Name_Full : " + d.Name_Full + "}"` is not valid JSON. Don't even try to build the string yourself; give `jsonify()` simple Python objects, like a list of dictionaries: `[{'Name_Full': d.Name_Full} for d in Defendants]`. – Martijn Pieters Aug 22 '15 at 16:10
  • the code you provided gives this error: dictionary update sequence element #0 has length 1; 2 is required – oppassum Aug 22 '15 at 16:16
  • You cannot pass that list directly to `jsonify()`, because that acts just like `dict()` does. You'll have to give it a key first, like `jsonify(results=[...])`. – Martijn Pieters Aug 22 '15 at 16:18
  • ok, considering json.dumps works similarly, I've switched to that. Here's the result I'm getting though: [{"Name_Full": "Smith, John"}, ...] how do I prevent it from encoding the ' marks? – oppassum Aug 22 '15 at 16:23
  • You are putting this into a HTML template? Then use the `listobject|json|safe` Jinja2 expression instead. – Martijn Pieters Aug 22 '15 at 16:25

0 Answers0