Search code examples
jsonneo4jpy2neo

outputiing py2neo query as JSON


I have tried looking all over but to no avail. Below is my cypher query in py2neo:

graph = Graph()
In [6]: query = """Match (C:Customer)-[r:Customer_Send]->(Send:Customer) where C.Galactic_ID = '2000000000084001287' return Send.Galactic_ID """

In [7]: graph.cypher.execute(query)


Out[7]:
       | Send.Galactic_ID
 ----+---------------------
      1 | 2000000000084114531
      2 | 1000000000284949451
      3 | 2000000000084114531
      4 | 1000000000213446086

I want the above output to be JSON formatted.


Solution

  • Below is the way to do it: I am sure this will be of immense help to the readers here:

    query = """Match (C:Customer)-[r:Customer_Send]->(Send:Customer) where C.Galactic_ID = '2000000000084001287' return Send.Galactic_ID as ID"""
    
    records = graph.cypher.execute(query,Customer='ID')
    returnObject = []
    
    In [11]: for record in records:
     ....:     returnObject.append(
     .  ...:     {
      ....:     'Customer':record.ID
         ....:     }
           ....:     )
    
    
    In [15]: returnObject
    Out[15]:
      [{'Customer': u'2000000000084114531'},
      {'Customer': u'1000000000284949451'},
      {'Customer': u'2000000000084114531'},
      {'Customer': u'1000000000213446086'},
      {'Customer': u'2000000000084114531'},
      {'Customer': u'2000000000127655859'},
      {'Customer': u'1000000000296804864'},
      {'Customer': u'2000000000084114531'},
      {'Customer': u'2000000000127655859'},
      {'Customer': u'2000000000127655859'},
      {'Customer': u'2000000000084114531'},
       {'Customer': u'1000000000213446086'}]
    
      from flask import json
    
    
      In [17]: x = json.dumps(returnObject)
    
      In [18]: x
       Out[18]: '[{"Customer": "2000000000084114531"}, {"Customer":   "1000000000284949451"}, {"Customer": "2000000000084114531"}, {"Customer": "1000000000213446086"}, {"Customer": "2000000000084114531"}, {"Customer": "2000000000127655859"}, {"Customer": "1000000000296804864"}, {"Customer": "2000000000084114531"}, {"Customer": "2000000000127655859"}, {"Customer": "2000000000127655859"}, {"Customer": "2000000000084114531"}, {"Customer": "1000000000213446086"}]'