Class: Tagcrumbs::JsonParser

Inherits:
Parser
  • Object
show all
Defined in:
lib/tagcrumbs/parsers/json_parser.rb

Overview

A parser for JSON

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parser_or_document) ⇒ JsonParser

Returns a new instance of JsonParser.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/tagcrumbs/parsers/json_parser.rb', line 6

def initialize(parser_or_document)
  if parser_or_document.is_a?(String)
    begin
      tmp = JSON.parse(parser_or_document)
      self._name = tmp.keys.first
      self.document = tmp[self._name]
    rescue JSON::ParserError # just a string (lowest level node in array)
      self.document = {'$' => parser_or_document }
    end
  elsif(parser_or_document.is_a?(Tagcrumbs::JsonParser))
    self.document = parser_or_document.document
  else
    self.document = parser_or_document
  end

  self.format = :json
end

Instance Attribute Details

#_nameObject

save the name of the json hash



4
5
6
# File 'lib/tagcrumbs/parsers/json_parser.rb', line 4

def _name
  @_name
end

Instance Method Details

#get_attribute(attribute) ⇒ Object

Get one attribute from the JSON



45
46
47
# File 'lib/tagcrumbs/parsers/json_parser.rb', line 45

def get_attribute(attribute)
  self.document["@#{attribute}"]
end

#get_attributesObject

Get all attributes from the badgerfish JSON that (all keys starting with ‘@’)



40
41
42
# File 'lib/tagcrumbs/parsers/json_parser.rb', line 40

def get_attributes
  attributes_from_badgerfish_json
end

#get_node(name) ⇒ Object

Get a node with a specific name from the document



25
26
27
# File 'lib/tagcrumbs/parsers/json_parser.rb', line 25

def get_node(name)
  self.document[name.to_s]
end

#get_valueObject

Get the value of an element (‘$’ key in badgerfish JSON)



50
51
52
# File 'lib/tagcrumbs/parsers/json_parser.rb', line 50

def get_value
  self.document['$']
end

#nameObject

Get the name of the current element



55
56
57
# File 'lib/tagcrumbs/parsers/json_parser.rb', line 55

def name
  _name || self.document.keys.select{|k| k.first != '@'}.first
end

#node_loaded?Boolean

Is this a stub and therefore only a “link” in the webservice or is a resource loaded?

Returns:

  • (Boolean)


30
31
32
# File 'lib/tagcrumbs/parsers/json_parser.rb', line 30

def node_loaded?
  badgerfish_json_loaded?
end

#nodes_with_name(name) ⇒ Object

Get all child nodes with a specific name



35
36
37
# File 'lib/tagcrumbs/parsers/json_parser.rb', line 35

def nodes_with_name(name)      
  self.document[name] || []
end