2017-10-18 71 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"