Module: Puppet::Util::Json
- Defined in:
- lib/puppet/util/json.rb
Defined Under Namespace
Classes: ParseError
Class Method Summary collapse
- .dump(object, options = {}) ⇒ Object
-
.load(string, options = {}) ⇒ Object
These methods do similar processing to the fallback implemented by MultiJson when using the built-in JSON backend, to ensure consistent behavior whether or not MultiJson can be loaded.
-
.load_file(filename, options = {}) ⇒ Object
Load the content from a file as JSON.
-
.load_file_if_valid(filename, options = {}) ⇒ Object
Load the content from a file as JSON if contents are in valid format.
Class Method Details
.dump(object, options = {}) ⇒ Object
81 82 83 84 85 86 87 88 89 90 91 |
# File 'lib/puppet/util/json.rb', line 81 def self.dump(object, = {}) if defined? MultiJson MultiJson.dump(object, ) elsif .is_a?(JSON::State) # we're being called recursively object.to_json() else .merge!(::JSON::PRETTY_STATE_PROTOTYPE.to_h) if .delete(:pretty) object.to_json() end end |
.load(string, options = {}) ⇒ Object
These methods do similar processing to the fallback implemented by MultiJson when using the built-in JSON backend, to ensure consistent behavior whether or not MultiJson can be loaded.
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/puppet/util/json.rb', line 50 def self.load(string, = {}) if defined? MultiJson begin # This ensures that JrJackson and Oj will parse very large or very small # numbers as floats rather than BigDecimals, which are serialized as # strings by the built-in JSON gem and therefore can cause schema errors, # for example, when we are rendering reports to JSON using `to_pson` in # PuppetDB. case MultiJson.adapter.name when "MultiJson::Adapters::JrJackson" [:use_bigdecimal] = false when "MultiJson::Adapters::Oj" [:bigdecimal_load] = :float end MultiJson.load(string, ) rescue MultiJson::ParseError => e raise Puppet::Util::Json::ParseError.build(e, string) end else begin string = string.read if string.respond_to?(:read) [:symbolize_names] = true if .delete(:symbolize_keys) ::JSON.parse(string, ) rescue JSON::ParserError => e raise Puppet::Util::Json::ParseError.build(e, string) end end end |
.load_file(filename, options = {}) ⇒ Object
Load the content from a file as JSON.
42 43 44 45 |
# File 'lib/puppet/util/json.rb', line 42 def self.load_file(filename, = {}) json = Puppet::FileSystem.read(filename, :encoding => 'utf-8') load(json, ) end |
.load_file_if_valid(filename, options = {}) ⇒ Object
Load the content from a file as JSON if contents are in valid format. This method does not raise error but returns ‘nil` when invalid file is given.
34 35 36 37 38 39 |
# File 'lib/puppet/util/json.rb', line 34 def self.load_file_if_valid(filename, = {}) load_file(filename, ) rescue Puppet::Util::Json::ParseError, ArgumentError, Errno::ENOENT => detail Puppet.debug("Could not retrieve JSON content from '#{filename}': #{detail.}") nil end |