我的第一个问题在这里!
我正在使用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 jsonify我的语句结果。请帮忙。
答案 0 :(得分:2)
问题是查询的结果是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)
答案 1 :(得分:1)
您也可以更改查询以获取JSON格式。
"MATCH (company:Company)-[]->(c) where c.name is not null RETURN COLLECT({company:company.name, name:c.name}) AS jsonOutput"