Module: Hatt::JsonHelpers

Included in:
HTTP, RequestException
Defined in:
lib/hatt/json_helpers.rb

Instance Method Summary collapse

Instance Method Details

#jsonify(obj) ⇒ Object

always returns a string, intended for request bodies every attempt is made to ensure string is valid json but if that is not possible, then its returned as is



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/hatt/json_helpers.rb', line 8

def jsonify(obj)
  case obj
  when String
    JSON.pretty_generate(JSON.parse(obj))
  when Hash, Array
    JSON.pretty_generate(obj)
  else
    obj.to_s
  end
rescue Exception
  obj.to_s
end

#objectify(json_string) ⇒ Object

attempts to parse json strings into native ruby objects



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/hatt/json_helpers.rb', line 22

def objectify(json_string)
  return nil if json_string.nil? || json_string == ''
  case json_string
  when Hash, Array
    return json_string
  else
    JSON.parse(json_string.to_s)
  end
rescue Exception
  json_string
end