簡體   English   中英

py2neo Neo4j TypeError: <map object at 0x03D25C50> 不可序列化為JSON

[英]py2neo Neo4j TypeError: <map object at 0x03D25C50> is not JSON serializable

from flask import Flask, jsonify, render_template
from py2neo import Graph,authenticate

app = Flask(__name__)
authenticate("localhost:7474","neo4j", "neo4j")
graph = Graph("http://localhost:7474/db/data")

def buildNodes(nodeRecord):
    print("............................")
    data = {"id": str(nodeRecord.n._id), "label": next(iter(nodeRecord.n.labels))}
    data.update(nodeRecord.n.properties)
    print(data)
    return {"data": data}

def buildEdges(relationRecord):
    data = {"source": str(relationRecord.r.start_node._id),
            "target": str(relationRecord.r.end_node._id),
            "relationship": relationRecord.r.rel.type}

    return {"data": data}

@app.route('/')
def index():
    print("index")
    return render_template('index.html')

@app.route('/graph')
def get_graph():
    # print(graph.cypher.execute('MATCH (n) RETURN n').columns)
    nodes = map(buildNodes, graph.cypher.execute('MATCH (n) RETURN n'))
    print(nodes)
    edges = map(buildEdges, graph.cypher.execute('MATCH ()-[r]->() RETURN r'))
    print(edges)
    # json_2={"nodes":nodes,"edges":edges}
    # return json.dumps(json_2, cls=UserEncoder)
    elements = {"nodes": nodes, "edges": edges}
    print(dict(elements))
    return jsonify(elements)
    return jsonify(elements)

if __name__ == '__main__':
    app.run(debug = False)

當我使用Python連接圖形數據庫(neo4j)時,出現問題'map object at 0x03D25C50' is not JSON serializable ,但map object at 0x03D25C50處的map object at 0x03D25C50map()方法的結果。 我不知道如何解決問題。

我在這里有什么明顯的誤區嗎?

對於圖像中的錯誤所表示的快速答案是,您沒有從except塊返回響應。 因此,由於try失敗,因此您的視圖未返回任何內容。 但這並不能回答真正的問題。 我沒有在python中使用map for循環和列表理解通常可以很好地完成工作。 我對neo4j也不陌生。 話雖如此,我相信答案是您正在使用__next__方法。 您為什么要明確地這樣做? 根據文檔,在遍歷可迭代對象以獲取下一組數據時使用此方法。 換句話說,當您遍歷一個Iterable時(例如使用for循環),它被隱式調用。 可能發生的情況是,如果只有一組數據,那么當您第一次調用__next__時,您將獲得第一個也是唯一的數據集。 但是,當您第二次調用它時,它沒有要返回的數據,因此您獲得了一個map object 這可能不是100%正確的答案,但是請嘗試刪除__next__調用,看看是否有幫助。 嘗試簡單地編碼str(edges)str(nodes)而不是調用__next__

在Python 2中,內置map返回了一個列表。 在Python 3中,它返回一個迭代器,而不是列表,而json模塊無法序列化該列表。 如果需要列表而不是迭代器,則應使用列表理解: [buildNodes(row) for row in graph.cypher.execute(...)] ,請使用[buildNodes(row) for row in graph.cypher.execute(...)] 您也可以通過執行list(map(...))來強制鍵入它,但這還不如listcomp清晰。

您應該意識到,不能在列表上調用__next__ (或者最好是next(...) ),因為這是一個迭代器方法。 不過,您可以打印整個列表而不消耗它,因此,除非您明確地嘗試延遲加載,否則無論如何,列表是一個更好的選擇。

您可以在此處閱讀有關標准文檔中列表/其他序列類型與迭代器之間的一些差異以及next內置函數的信息,以及為什么在此處 __next__更可取。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM