How to convert Neo4j response into JSON

450 Views Asked by At

Convert stream of records from NEO4j get by NEO4J python driver into JSON. simply, I want to convert the results of cypher queries in neo4j into a JSON format. Below is output got from NEO4J

<Record n=<Node id=3099 labels=frozenset({'BusinessData'}) properties={'Description': 'sample description.', 'x-NodeCreated': neo4j.time.Date(2023, 1, 11), 'name': 'Example', 'GUID': 'KL12822', 'Notes': 'Deployed', 'x-LastEdit': '16445676677MN'}>>

The result from a query looks something like above and When I perform a simple json.dumps() it return with TypeError: Object of type is not JSON serializable.

json_data = json.dumps(info,default = str)

What I am asking here is a way to get, What is the correct way to convert the query results to JSON!

1

There are 1 best solutions below

0
On

One pattern that I quite like for this type of use case is to use Cypher's map projection feature to return a map/dictionary/object which can be more easily converted to JSON. Here's an example:

WITH point({latitude: $latitude, longitude:$longitude}) AS radiusCenter
MATCH (p:Point)-[:HAS_GEOMETRY]-(poi:PointOfInterest)-[:HAS_TAGS]->(t:Tags) 
WHERE point.distance(p.location, radiusCenter) < $radius
RETURN p {  
  latitude: p.location.latitude, 
  longitude: p.location.longitude, 
  name: poi.name, 
  categories: labels(poi),
  tags: t{.*}
} AS point

The above Cypher query will return a list of records, where each record is a map/dictionary/object:

{  
  latitude: 45.0, 
  longitude: -137.43, 
  name: "West Side Bakery", 
  categories: ['Bakery', 'PointOfInterest'],
  tags: [
    address: "1234 Main St",
    commercial: "Bakery"
  ]
}

Then in your python code you can add each point record to a list and convert to JSON (another option would be to COLLECT in your Cypher statement and return a single array/list of objects):

point_list = []

with driver.session() as session:
    results = session.execute_read(
        lambda tx: tx.run(MY_CYPHER_QUERY).data()
    )
    for record in results:
        point_list.append(record)