Skip to content Skip to sidebar Skip to footer

Exporting Data From Neo4j To Csv Instead Of Json

I'm using neo4jdb-python packages to query the Neo4j database. For example, considering the below code import neo4j connection = neo4j.connect('http://localhost:7474') cursor = co

Solution 1:

The Neo4j Server returns only JSON, as Mark Needham mentions in his answer.

Hence any code to do convert it to CSV must be on the client side. This can be done using the csv module. Note that neo4jdb-python package is compatible with Python2.7 only.

A minimal code for obtaining the data is

import neo4j
connection = neo4j.connect("http://localhost:7474")
cursor = connection.cursor()
data = list(cursor.execute("MATCH a RETURN a LIMIT 1")

Note that as mentioned in the question the returned values are in the form of tuples. The minimal code to create the csv file is

with open("test.csv","w") as csvfile:
    writer = csv.writer(csvfile,delimiter = ',',quotechar = '"',quoting = csv.QUOTE_ALL)
    writer.writerow(t[0].keys())
    foriin t:
        writer.writerow(['{"%s":"%s"}'%(k,v) fork,v in i.iteritems()])

The explanation for the code is simple, open a file. Using csv.writer, create a writer object. Write the header first using writerow. Finally loop through the dictionary and write the rows.

The output obtained is

"{""text"":""Stoyanov, S., Hoogveld, B., Kirschner, P.A., (2010). Mapping Major Changes to Education and Training in 2025, in JRC Technical Note JRC59079., Publications Office of the European Union: Luxembourg.""}","{""identifier"":""reference/lak/226""}"

which is similar to that obtained using the exportable.coffee script.

Solution 2:

That CSV isn't actually coming from a particular API - it's being translated into CSV format on the client side.

The appropriate code is in exportable.coffee if you want to take a look:

    $scope.exportCSV = (data) ->
      return unless data
      csv = new CSV.Serializer()
      csv.columns(data.columns())
      for row indata.rows()
        csv.append(row)

And that refers to CSV.coffee. I guess you should be able to do something similar in Python perhaps using json.dumps like this:

> import json
> t = ({u'text': u'Stoyanov, S., Hoogveld, B., Kirschner, P.A., (2010). Mapping Major Changes to Education and Training in 2025, in JRC Technical Note JRC59079., Publications Office of the European Union: Luxembourg.', u'identifier': u'reference/lak/226'},)
> json.dumps(t)
 '[{"text": "Stoyanov, S., Hoogveld, B., Kirschner, P.A., (2010). Mapping Major Changes to Education and Training in 2025, in JRC Technical Note JRC59079., Publications Office of the European Union: Luxembourg.", "identifier": "reference/lak/226"}]'

Post a Comment for "Exporting Data From Neo4j To Csv Instead Of Json"