Export Graph in R via JSON

This post presents an easy solution for exporting and importing a graph object of igraph library.
In its previous versions, the library used to have the save and load functions in which you could respectively export and import the graph object [1]. Although they seem to not be in the library anymore, the documentation states:

“Attribute values can be set to any R object, but note that storing the graph in some file formats might result the loss of complex attribute values. All attribute values are preserved if you use save and load to store/retrieve your graphs.

The library also proposes write_graph and read_graph, that rely on the GraphML format, for exporting and importing back graph objects.

However, here I propose my little solution with almost zero options. It saves the graph and allows to re-load it again (in another session as well) simply saving all the fields and values in a JSON file.

From R to JSON:

exportGraph(graph_object, "output_file.json") #saving in a file

or

object_json <- exportGraph(graph_object) #converting graph to JSON

This function requires the graph object and the ouptut file (although this fields is not mandatory, you can decide to not save the graph into a file but converting it only to JSON instead). It returns a JSON string.

From JSON to R:

imported_graph_object <- importGraph("input_file.json") #from JSON file

or

imported_graph_object <- importGraph(input_object_json) #from JSON string

This function, instead, requires either the JSON file  or the JSON object (character array) that contains the graph. It returns, then, the graph object.

Example:

#some graphs:
#1 
g1 <- graph(c(1,2,1,3,1,4,2,3,3,4,4,5,4,6,5,6,5,8,5,7,6,8,6,7,7,8,7,9), directed=F)
#2
g2 <- make_graph("Zachary") #the karate network

#export-import on json string
out.json <- exportGraph(g1)
imported.g1 <- importGraph(out.json)

#export-import on json file
exportGraph(g2,"zachary.json")
imported.g2 <- importGraph("zachary.json")

#another fancy way to copy a graph through JSON
g2.copy <- importGraph(exportGraph(g2))

Project info

Github repository:  https://github.com/angelosalatino/graph-importer-R

References

[1] Page saved on 29th March 2017: Package ‘igraph’. https://web.archive.org/web/20170329213648/http://igraph.org/r/doc/igraph.pdf