【问题标题】:Make cassandra object json serializable使 cassandra 对象 json 可序列化
【发布时间】:2019-08-29 08:00:30
【问题描述】:

我有一种方法可以从 cassandra 数据库中获取我的所有数据。我面临的问题是它返回一个 cassandra 对象,而我想要 json。我尝试了多种解决方案,但似乎都没有。我试过 json.dumps()loads 但我收到一条错误消息说 object is not JSON serializable

有什么建议吗?

我的代码:

@api.route('/getAllApps')
class getAllApps(Resource):
    @api.marshal_list_with(model)
    def get(self):
        return ar.getAllApplications(), 200
        #if ar.getAllApplications is None:
            #return 204



def getAllApplications(*args):
        for data in AddApplication.objects():
             print(data, data.address, data.gocd, data.jenkins, data.nodes, data.serverDependencies)
             return data

【问题讨论】:

  • 您需要将object_hook 传递给json.loads
  • 请不要尝试从 Cassandra 获取所有数据!如果你有相对大的数据,你会杀死你的集群

标签: python json object cassandra


【解决方案1】:

按照默认设置,cassandra 以元组格式返回查询数据。您需要做的是更改 cassandra 配置以以 dict 格式接收它。

import json
from cassandra.query import ordered_dict_factory

cluster = Cluster(['127.0.0.1'],auth_provider=auth_provider)
session = cluster.connect("keyspace")
session.row_factory = ordered_dict_factory

#query result
rows = self.session.execute_async("SELECT * FROM " + table)
rows = self.return_result(rows, 'data')
data = rows.result()

# dump in json
json.dumps(data)

这是另一种方式,请查看select-json支持:

 SELECT JSON a, ttl(b) FROM ...

【讨论】:

  • 谢谢!完美运行。
猜你喜欢
  • 2010-11-30
  • 2013-09-04
  • 1970-01-01
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多