Allows setting the format with which to parse.
 Must be one of the allowed formats ie: json, xml

   class Foo
     include HTTParty
     format :json
   end
336177
def format(f = nil)
      if f.nil?
        default_options[:format]
      else
        parser(Parser) if parser.nil?
        default_options[:format] = f
        validate_format
      end
    end
827280
def parse_response(response, format = 'json')
      result = nil

      if format == 'json'
        result = JSON.parse(response)
      elsif format == 'xml'
        result = Nokogiri::XML(response)
      end

      return result
    end
1263530
def parse_json(response)
      return nil if response.body.empty?
      
      JSON.parse(response.body)
    rescue => ex
      raise Kontena::Errors::StandardError.new(520, "Invalid response JSON from server for #{response.path}: #{ex.class.name}: #{ex.message}")
    end
714487
def format(value, name = nil, style = nil)
      name  ||= self.name
      style ||= self.style

      value = fixed if fixed
      value ||= default if default

      unless value
        if required?
          raise ArgumentError, %Q{No value provided for required param "#{name}"!}
        else
          return '' # No value provided and none required.
        end
      end

      if value.respond_to?(:each) && !value.respond_to?(:to_str)
        if repeating?
          values = value
        else
          raise ArgumentError, %Q{Multiple values provided for single-value param "#{name}"}
        end
      else
        values = [value]
      end

      # If the param lists acceptable values in option tags, make sure that
      # all values are found in those tags.
      if options && !options.empty?
        values.each { |_value|
          unless find_option(_value)
            acceptable = options.map { |o| o.value }.join('", "')
            raise ArgumentError, %Q{"#{_value}" is not among the acceptable parameter values ("#{acceptable}")}
          end
        }
      end

      if style == 'query' || parent.is_a?(RequestFormat) || (
        parent.respond_to?(:is_form_representation?) && parent.is_form_representation?
      )
        values.map { |v| "#{uri_escape(name)}=#{uri_escape(v.to_s)}" }.join('&')
      elsif style == 'matrix'
        if type == 'xsd:boolean'
          values.map { |v| ";#{name}" if v =~ BOOLEAN_RE }.compact.join
        else
          values.map { |v| ";#{uri_escape(name)}=#{uri_escape(v.to_s)}" if v }.compact.join
        end
      elsif style == 'header'
        values.join(',')
      else
        # All other cases: plain text representation.
        values.map { |v| uri_escape(v.to_s) }.join(',')
      end
    end
348852
def set_datetime_format(self, format):
        
        if not format in ["UNIX", "RFC3339"]:
            return

        self.datetime_format = format

        self.set_header("Accept-Datetime-Format", self.datetime_format)
1003835
def prepare_and_invoke_api_call(path, options = {})
      api_call = prepare_api_call(path, options)
      data = invoke_api_call(api_call)

      parsed_data = case options[:format]
        when 'json' then JSON.parse(data)
        when 'xml' then REXML::Document.new(data)
        else JSON.parse(data) rescue REXML::Document.new(data) rescue data
      end
      RubyDesk.logger.info "Parsed data: #{parsed_data.inspect}"
      return parsed_data
    end
873678
def _put_or_post_json(self, method, url, data):
        
        if self.parsed_endpoint.scheme == 'https':
            conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc)
        else:
            conn = httplib.HTTPConnection(self.parsed_endpoint.netloc)
        head = {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "User-Agent": USER_AGENT,
            API_TOKEN_HEADER_NAME: self.api_token,
        }
        if self.api_version in ['0.1', '0.01a']:
            head[API_VERSION_HEADER_NAME] = self.api_version
        conn.request(method, url, json.dumps(data), head)
        resp = conn.getresponse()
        self._handle_response_errors(method, url, resp)
        return json.loads(resp.read())
926714
def check_format(formats, input)
      formats.inject(true) do |result, (key, format)|
        format.call(input[key]) && result
      end
    end
1097653
def jsonify(obj)
      case obj
      when String
        JSON.pretty_generate(JSON.parse(obj))
      when Hash, Array
        JSON.pretty_generate(obj)
      else
        obj.to_s
      end
    rescue Exception
      obj.to_s
    end
946215
def _format(self, ans, q):
        
        if 'fmt' in q:
            fmt = q['fmt'][0]
        else:
            fmt = 'json'

        fmt = fmt.lower()

        if fmt in self._formatters:
            return (200, self._formatters[fmt](ans, q), 'application/json')
        else:
            return (415,
                'Invalid fmt request "%s", supported formats are: %s\n'%
                    (fmt, ' '.join(self._formatters.keys()),),
                'text/plain')
978366
def select_header_accept(accepts)
      if accepts.empty?
        return
      elsif accepts.any?{ |s| s.casecmp('application/json') == 0 }
        'application/json' # look for json data by default
      else
        accepts.join(',')
      end
    end
738265
def parse(data)
      if !data.respond_to?(:read)
        data = StringIO.new(data || "")
      end

      if data.eof?
        {}
      else
        LibXML::XML::Parser.io(data).parse.to_hash
      end
    end
211429
def set(options)
      json_body = options.to_json
      request_uri = "#{base_request_uri}/state"
      HTTParty.put(request_uri, :body => json_body)
    end
175954
def json_schema_validation_format(value, schema_validation_type):
    
    DEFAULT_FORMAT_VALIDATORS['date-time'] = validate_format_iso8601
    DEFAULT_FORMAT_VALIDATORS['text'] = validate_format_text
    validictory.validate(value, schema_validation_type, format_validators=DEFAULT_FORMAT_VALIDATORS)
537626
def parse_response(response)
      check_version_and_warn(response.headers[X_KONTENA_VERSION])

      if response.headers[CONTENT_TYPE] =~ JSON_REGEX
        parse_json(response)
      else
        response.body
      end
    end
184939
def parse(cls, format):
        

        fmt = cls()

        # Return an empty Format if format is empty
        if not format:
            return fmt

        # Initialize the state for parsing
        state = ParseState(fmt, format)

        # Loop through the format string with a state-based parser
        for idx, char in enumerate(format):
            # Some characters get ignored
            if state.check_ignore():
                continue

            if state == 'string':
                if char == '%':
                    # Handle '%%'
                    if format[idx:idx + 2] == '%%':
                        # Add one % to the string context
                        state.add_text(idx + 1, idx + 2)
                        state.set_ignore(1)
                    else:
                        state.add_text(idx)
                        state.conversion(idx)
                elif char == '\\':
                    state.add_text(idx)
                    state.escape(idx)
            elif state == 'escape':
                state.add_escape(idx + 1, char)
                state.pop_state(idx + 1)
            elif state == 'param':
                if char == '}':
                    state.set_param(idx)
                    state.pop_state()
            elif state == 'conv':
                if char == ')':
                    state.set_conversion(idx)
                    state.pop_state()  # now in 'conversion'
                    state.pop_state(idx + 1)  # now in 'string'
            else:  # state == 'conversion'
                if char in '<>':
                    # Allowed for Apache compatibility, but ignored
                    continue
                elif char == '!':
                    state.set_reject()
                    continue
                elif char == ',' and state.code_last:
                    # Syntactically allowed ','
                    continue
                elif char.isdigit():
                    # True if the code is valid
                    if state.set_code(idx):
                        continue
                elif char == '{' and state.param_begin is None:
                    state.param(idx + 1)
                    continue
                elif char == '(' and state.conv_begin is None:
                    state.conv(idx + 1)
                    continue

                # OK, we have a complete conversion
                state.set_conversion(idx)
                state.pop_state(idx + 1)

        # Finish the parse and return the completed format
        return state.end_state()
241840
function parse_messages (parser_type, str) {
  var parser = new HTTPParser(parser_type);
  var buffer = new Buffer(str, 'utf-8');
  var output = [];

  parser.onMessageBegin = function() {
    output.push({
      versionMajor: undefined,
      versionMinor: undefined,
      method: undefined,
      uri: undefined,
      statusCode: undefined,
      headers: {},
      body: "",
      complete: false
    });
    parser.field = null;
    parser.value = null;
  };

  parser.onURL = function(b, start, len) {
    var slice = b.toString('ascii', start, start + len);
    if (output[output.length-1].url) {
      output[output.length-1].url += slice;
    } else {
      // Almost always will branch here.
      output[output.length-1].url = slice;
    }
  };
  
  parser.onHeaderField = function(b, start, len) {
    var slice = b.toString('ascii', start, start + len).toLowerCase();
    if (parser.value != undefined) {
      // note that this overwrites dup headers
      output[output.length-1].headers[parser.field] = parser.value;
      parser.field = null;
      parser.value = null;
    }
    if (parser.field) {
      parser.field += slice;
    } else {
      parser.field = slice;
    }
  };

  parser.onHeaderValue = function(b, start, len) {
    var slice = b.toString('ascii', start, start + len);
    if (parser.value) {
      parser.value += slice;
    } else {
      parser.value = slice;
    }
  };

  parser.onHeadersComplete = function(info) {
    if (parser.field && (parser.value != undefined)) {
      output[output.length-1].headers[parser.field] = parser.value;
      parser.field = null;
      parser.value = null;
    }

    output[output.length-1].versionMajor = info.versionMajor;
    output[output.length-1].versionMinor = info.versionMinor;
    output[output.length-1].statusCode = info.statusCode;
    output[output.length-1].method = info.method;

    return false // isHeadResponse;
  };

  parser.onBody = function(b, start, len) {
    var slice = b.slice(start, start + len);
    output[output.length-1].body += slice;
  };

  parser.onMessageComplete = function() {
    output[output.length-1].complete = true;
    if (parser.field && (parser.value != undefined)) {
      output[output.length-1].headers[parser.field] = parser.value;
    }  
  }
  
  parser.execute(buffer, 0, buffer.length);
  
  // filter out incomplete responses.
  var complete_output = [];
  output.forEach(function (o) {
    if (o.complete) {
      complete_output.push(o);
    }
  })
  return complete_output;
}