How to serialize neo4j.graph.Node to JSON

my execute_write is calling a function that runs a merge statement that returns a node

return = tx.run ( ..... ).single()
return [ record["p"] for record in result ]

the output of cypher is something like this

<Record p=<Node element_id='4:f4673382-5e4c-42ad-b499-792e15616d9a:170' labels=frozenset({'PartRevisionSH'}) properties={'name': 'susan', 'revid': 'sRev', 'revisionRule': ['SRule'], 'id': 's0002'}>>

I want to serialize the output node to JSON
i am getting this error in my flask application

aise TypeError(f"Object of type {type(o).name} is not JSON serializable")
TypeError: Object of type ABCMeta is not JSON serializable

TypeError: Object of type ABCMeta is not JSON serializable

what are the approaches to generate JSON representations from neo4j.graph.Node or neo4j.graph.Relationship type?

Hi @shsamardar ,

I'm not aware of an API call in the Python driver that will provide a JSON serializable object, so I drafted a custom JSONEncoder here:

Which can be used like this:

    result = # get a result from Neo4j for `MATCH (n)-[r]->() return n,r`
    record = result.single()[0]
    print("node as json:",json.dumps(record.get("n"), cls=GraphElementEncoder))
    print("relationship as json:",json.dumps(record.get("r"), cls=GraphElementEncoder))

Producing a result like:

node as json: {"element_id": "1", "labels": ["Actor"], "properties": {"name": "Tom Hanks"}}
relationship as json: {"element_id": "0", "type": "ACTED_IN", "properties": {}, "start_element_id": "1", "end_element_id": "0"}

Would that work for you?

-ABK

1 Like

You can use the apoc.convert.toJson() function to convert the node to a json representation, or any cypher map to json.

Do this in cypher to return it as a string.