How to get a json type from cassandra using python

1,145 views
Skip to first unread message

凸鎚大法師

unread,
Mar 31, 2018, 9:06:39 AM3/31/18
to DataStax Python Driver for Apache Cassandra User Mailing List

I'm trying to get JSON from Cassandra, but I do'know how do it.

assets_idx is SortedSet of cassandra data type , 
please tell me , how do get a json type from set type?

thank you




import json
import uuid
from cassandra.cqlengine import columns
from cassandra.cqlengine.models import Model
from cassandra.cqlengine import connection
from cassandra.cqlengine.management import sync_table

class Person(Model):
    __table_name__  
= 'useridindex'
    __keyspace__
= 'testdb'
    __connection__
= 'cluster2'


    id
= columns.UUID(primary_key=True, default=uuid.uuid4)
    first_name
= columns.Text()
    last_name
= columns.Text()
    assets_idx
= columns.Set(columns.Integer())

   
def get_data(self):
       
return {
           
'id': str(self.id),
           
'first_name': self.first_name,
           
'last_name': self.last_name,
           
'assets_idx' : self.........
   
}

def cassandraTest():
    cluster
= Cluster(contact_points=['localhost'], port=9042)
    session
= cluster.connect()


    connection
.register_connection('cluster2', session=session)
    create_keyspace_simple
('testdb', 1, connections=['cluster2'])
    sync_table
(Person)

   
Person.create(first_name='jack', last_name='chen' ,  assets_idx={111, 2222, 3333})
   
Person.save()
   
persons = Person.objects().all()
  
    jsonObj =
[person.get_data() for person in persons]


    print(json.dumps(jsonObj, indent=4 ,ensure_ascii=False));

if __name__ == '__main__':
    cassandraTest
()


Alex Ott

unread,
Apr 3, 2018, 5:25:58 PM4/3/18
to python-dr...@lists.datastax.com
Hi

Because JSON has no notion of sets, you need to convert set object into list object, by calling list on it, like this:

json.dumps(list({111, 2222, 3333}))

P.S. I believe that this is slightly offtopic for this list


--
You received this message because you are subscribed to the Google Groups "DataStax Python Driver for Apache Cassandra User Mailing List" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python-driver-user+unsub...@lists.datastax.com.



--
With best wishes,                    Alex Ott
http://alexott.net/
Twitter: alexott_en (English), alexott (Russian)

Alan Boudreault

unread,
Apr 3, 2018, 5:25:58 PM4/3/18
to python-dr...@lists.datastax.com
Hi,

The simpler solution is to convert the set to a list.

Regards,
Alan

--
You received this message because you are subscribed to the Google Groups "DataStax Python Driver for Apache Cassandra User Mailing List" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python-driver-user+unsub...@lists.datastax.com.



--

Alan Boudreault
Software Engineer (Drivers) | alan.bo...@datastax.com


Reply all
Reply to author
Forward
0 new messages