Module: JSONGraph

Defined in:
lib/graphs/json.rb

Overview

JSON-related functions

Class Method Summary collapse

Class Method Details

.load(filename) ⇒ Object

Loads a JSON file and return a new Graph object

Parameters:

  • filename (String)

    a valid filename

See Also:

  • parse


33
34
35
# File 'lib/graphs/json.rb', line 33

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

.parse(content) ⇒ Object

Parse some JSON text and return a new Graph object

Parameters:

  • content (String)

    a valid GDF String

See Also:

  • load
  • unparse


41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/graphs/json.rb', line 41

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) ⇒ Object

Return a JSON String which describe the given Graph

Parameters:

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

    A customizable set of options

See Also:



59
60
61
62
63
64
65
# File 'lib/graphs/json.rb', line 59

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