module Puppet::Util::Json
Public Class Methods
dump(object, options = {})
click to toggle source
# File lib/puppet/util/json.rb 81 def self.dump(object, options = {}) 82 if defined? MultiJson 83 MultiJson.dump(object, options) 84 elsif options.is_a?(JSON::State) 85 # we're being called recursively 86 object.to_json(options) 87 else 88 options.merge!(::JSON::PRETTY_STATE_PROTOTYPE.to_h) if options.delete(:pretty) 89 object.to_json(options) 90 end 91 end
load(string, options = {})
click to toggle source
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.
# File lib/puppet/util/json.rb 50 def self.load(string, options = {}) 51 if defined? MultiJson 52 begin 53 # This ensures that JrJackson and Oj will parse very large or very small 54 # numbers as floats rather than BigDecimals, which are serialized as 55 # strings by the built-in JSON gem and therefore can cause schema errors, 56 # for example, when we are rendering reports to JSON using `to_pson` in 57 # PuppetDB. 58 case MultiJson.adapter.name 59 when "MultiJson::Adapters::JrJackson" 60 options[:use_bigdecimal] = false 61 when "MultiJson::Adapters::Oj" 62 options[:bigdecimal_load] = :float 63 end 64 65 MultiJson.load(string, options) 66 rescue MultiJson::ParseError => e 67 raise Puppet::Util::Json::ParseError.build(e, string) 68 end 69 else 70 begin 71 string = string.read if string.respond_to?(:read) 72 73 options[:symbolize_names] = true if options.delete(:symbolize_keys) 74 ::JSON.parse(string, options) 75 rescue JSON::ParserError => e 76 raise Puppet::Util::Json::ParseError.build(e, string) 77 end 78 end 79 end
load_file(filename, options = {})
click to toggle source
Load the content from a file as JSON.
# File lib/puppet/util/json.rb 42 def self.load_file(filename, options = {}) 43 json = Puppet::FileSystem.read(filename, :encoding => 'utf-8') 44 load(json, options) 45 end
load_file_if_valid(filename, options = {})
click to toggle source
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.
# File lib/puppet/util/json.rb 34 def self.load_file_if_valid(filename, options = {}) 35 load_file(filename, options) 36 rescue Puppet::Util::Json::ParseError, ArgumentError, Errno::ENOENT => detail 37 Puppet.debug("Could not retrieve JSON content from '#{filename}': #{detail.message}") 38 nil 39 end