self.parse_json

in cookbooks/fb_helpers/libraries/fb_helpers.rb [352:386]


    def self.parse_json(json_string, top_level_class = Hash, fallback = false)
      unless [Array, Hash, String].include?(top_level_class)
        fail 'fb_helpers: top_level_class can only be Array, Hash or ' +
          "(actual: #{top_level_class})"
      end

      begin
        parsed_json = Chef::JSONCompat.parse(json_string)
      rescue Chef::Exceptions::JSON::ParseError => e
        m = 'fb_helpers: cannot parse string as JSON; returning an empty ' +
            "#{top_level_class} instead: #{e}"
        if fallback
          Chef::Log.error(m)
          return top_level_class.new
        else
          
          fail m
          
        end
      end

      unless parsed_json.is_a?(top_level_class)
        m = 'fb_helpers: parsed JSON does not match the expected ' +
            "#{top_level_class} (actual: #{parsed_json.class})"
        if fallback
          Chef::Log.error(m)
          return top_level_class.new
        else
          fail m
        end
      end

      parsed_json
    end