Class: Chef::JSONCompat
- Inherits:
-
Object
- Object
- Chef::JSONCompat
- Defined in:
- lib/chef/json_compat.rb
Class Method Summary collapse
- .from_json(source, opts = {}) ⇒ Object
- .parse(source, opts = {}) ⇒ Object
- .to_json(obj, opts = nil) ⇒ Object
- .to_json_pretty(obj, opts = nil) ⇒ Object
Class Method Details
.from_json(source, opts = {}) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/chef/json_compat.rb', line 36 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
30 31 32 33 34 |
# File 'lib/chef/json_compat.rb', line 30 def parse(source, opts = {}) FFI_Yajl::Parser.parse(source, opts) rescue FFI_Yajl::ParseError => e raise Chef::Exceptions::JSON::ParseError, e. end |
.to_json(obj, opts = nil) ⇒ Object
49 50 51 52 53 |
# File 'lib/chef/json_compat.rb', line 49 def to_json(obj, opts = nil) FFI_Yajl::Encoder.encode(obj, opts) rescue FFI_Yajl::EncodeError => e raise Chef::Exceptions::JSON::EncodeError, e. end |
.to_json_pretty(obj, opts = nil) ⇒ Object
55 56 57 58 59 |
# File 'lib/chef/json_compat.rb', line 55 def to_json_pretty(obj, opts = nil) = { pretty: true } [:indent] = opts[:indent] if opts.respond_to?(:key?) && opts.key?(:indent) to_json(obj, ).chomp end |