Module: JSONGraph

Defined in:
lib/graphs/json.rb

Overview

JSON-related functions

Class Method Summary collapse

Class Method Details

.load(filename) ⇒ Graph

Loads a JSON file and return a new Graph object

Parameters:

  • filename (String)

    a valid filename

Returns:

See Also:



36
37
38
# File 'lib/graphs/json.rb', line 36

def self.load(filename)
    self.parse(File.read(filename))
end

.parse(content) ⇒ Graph

Parse some JSON text and return a new Graph object

Parameters:

  • content (String)

    a valid GDF String

Returns:

See Also:



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/graphs/json.rb', line 45

def self.parse(content)

    if (content.nil? || content.length == 0)
        return Graph.new([],[])
    end

    content = JSON.parse content

    nodes = content['nodes']
    edges = content['edges']

    Graph.new(nodes, edges)
end

.unparse(graph, opts = nil) ⇒ String

Return a JSON String which describe the given Graph

Parameters:

  • graph (Graph)
  • opts (Hash) (defaults to: nil)

    A customizable set of options

Returns:

  • (String)

See Also:



64
65
66
67
68
69
70
# File 'lib/graphs/json.rb', line 64

def self.unparse(graph, opts=nil)

    nodes = graph.nodes.map { |n| n.to_hash }
    edges = graph.edges.map { |e| e.to_hash }

    JSON.dump({ 'nodes' => nodes, 'edges' => edges })
end