2

I am writing an API which queries a Cassandra 2.1.2 based database and returns results in JSON format. I am using cqlengine for this.

Here is the simplified schema -

class Checkins(Model):
    Model.__comment__ = "Table mapping for submit datastore"
    changelist     =  columns.Integer (primary_key= True)                                 # Changelist number
    checkin_date   =  columns.DateTime()                                                  # Submit time
    stream_name    =  columns.Ascii   (primary_key= True)                                 # Stream-name
    creator        =  columns.Ascii   ()                                                  # Creator

My query is this

clobj = Checkins.objects(changelist=changelist).get()

How do I convert the resultset into a json format ?

Arovit
  • 3,579
  • 5
  • 20
  • 24

1 Answers1

0

You can create dictionaries from models as of cqlengine 0.12. From there you can use the json module to get a JSON format. You do have to be careful because datetimes are not json serializable. Therefore you will need to convert it to a string first (Or look at this question for other ways to fix the datetime serialization problem).

import json

clobj = Checkins.objects(changelist=changelist).get()
clobj_dict = dict(clobj_dict)
clobj_dict['checkin_date'] = str(clobj_dict['checkin_date'])
json_string = json.dumps(clobj_dict)

or you could add it as a property on the class

import json

class Checkins(Model):
    # Define your model as before
    # ...

    @property
    def json(self):
        # Perform the same thing as before.
        json_dict = dict(self)
        json_dict['checkin_date'] = str(json_dict['checkin_date'])
        return json.dumps(clobj_dict)

# Just call the property.
clobj = Checkins.objects(changelist=changelist).get()
json_string = clobj.json
Community
  • 1
  • 1
Tim Martin
  • 2,419
  • 1
  • 21
  • 25