2017-10-18 67 views
1

我的第一个问题在这里!jsonify bolt statementresult

我正在开发使用python和flask的webservices。 Neo4j是我想要APIfy的后端。

我对图形数据库运行匹配查询并希望返回一个json对象。以下是代码。

from flask import Flask, jsonify 
from neo4j.v1 import GraphDatabase 

app = Flask(__name__) 

uri = "bolt://localhost:7687" 
driver = GraphDatabase.driver(uri, auth=(user, pass)) 

@app.route('/') 
def com_relations(): 
    with driver.session() as session: 
     with session.begin_transaction() as tx: 
      return jsonify(tx.run("MATCH (company:Company)-[]->(c) where c.name is not null " 
          "RETURN company.name, c.name")) 

     session.close() 

但是在运行应用程序时出现错误。

TypeError: Object of type 'BoltStatementResult' is not JSON serializable 

我明白错误,我想知道如何从neo4j中声明我的声明结果。请帮忙。

回答

1

问题是查询的结果是StatementResult object,它不能被“序列化”。因此,您需要先准备如下结果:

from flask import Flask, jsonify 
from neo4j.v1 import GraphDatabase 

app = Flask(__name__) 

uri = "bolt://localhost:7687" 
driver = GraphDatabase.driver(uri, auth=(user, pass)) 

@app.route('/') 
def com_relations(): 
    with driver.session() as session: 
     with session.begin_transaction() as tx: 
      results = (tx.run("MATCH (company:Company)-[]->(c) where c.name is not null" 
           "RETURN company.name, c.name"))  
     session.close() 
     records = [] 
     for record in results: 
      records.append({"company.name": record["company.name"], 
          "name": record["c.name"]}) 
     return jsonify(records) 
+0

谢谢!这几乎是我用作替代品的地方。我有另一个想法,如果有其他方法序列化一个statementResult对象...感谢您的时间。 – Amsa

0

您还可以更改查询以获取JSON格式。

"MATCH (company:Company)-[]->(c) where c.name is not null RETURN COLLECT({company:company.name, name:c.name}) AS jsonOutput"