Class: Chef::JSONCompat

Inherits:
Object
  • Object
show all
Defined in:
lib/chef/json_compat.rb

Constant Summary collapse

JSON_MAX_NESTING =
1000

Class Method Summary collapse

Class Method Details

.from_json(source, opts = {}) ⇒ Object

Just call the JSON gem’s parse method with a modified :max_nesting field



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/chef/json_compat.rb', line 39

def from_json(source, opts = {})
  obj = parse(source, opts)

  # JSON gem requires top level object to be a Hash or Array (otherwise
  # you get the "must contain two octets" error). Yajl doesn't impose the
  # same limitation. For compatibility, we re-impose this condition.
  unless obj.is_a?(Hash) || obj.is_a?(Array)
    raise Chef::Exceptions::JSON::ParseError, "Top level JSON object must be a Hash or Array. (actual: #{obj.class})"
  end

  obj
end

.parse(source, opts = {}) ⇒ Object

API to use to avoid create_addtions



32
33
34
35
36
# File 'lib/chef/json_compat.rb', line 32

def parse(source, opts = {})
  FFI_Yajl::Parser.parse(source, opts)
rescue FFI_Yajl::ParseError => e
  raise Chef::Exceptions::JSON::ParseError, e.message
end

.to_json(obj, opts = nil) ⇒ Object



52
53
54
55
56
# File 'lib/chef/json_compat.rb', line 52

def to_json(obj, opts = nil)
  FFI_Yajl::Encoder.encode(obj, opts)
rescue FFI_Yajl::EncodeError => e
  raise Chef::Exceptions::JSON::EncodeError, e.message
end

.to_json_pretty(obj, opts = nil) ⇒ Object



58
59
60
61
62
63
64
# File 'lib/chef/json_compat.rb', line 58

def to_json_pretty(obj, opts = nil)
  opts ||= {}
  options_map = {}
  options_map[:pretty] = true
  options_map[:indent] = opts[:indent] if opts.key?(:indent)
  to_json(obj, options_map).chomp
end