The json_parser plugin parses request bodies in JSON format if the request’s content type specifies json. This is mostly designed for use with JSON API sites.
This only parses the request body as JSON if the Content-Type header for the request includes “json”.
The parsed JSON body will be available in r.POST, just as a parsed HTML form body would be. It will also be available in r.params (which merges r.GET with r.POST).
Classes and Modules
Constants
| DEFAULT_ERROR_HANDLER | = | proc{|r| r.halt [400, {}, []]} |
Public Class methods
Handle options for the json_parser plugin:
| :content_type_regexp |
A regexp used to determine if the request’s content type is JSON. For backwards compatibility, uses the insecure /json/ if not provided. Warns if this option is not provided. The recommended value to use is /Aapplication/jsonb/i or /Aapplication/(?:vnd.api+)?jsonb/i. |
| :error_handler |
A proc to call if an exception is raised when parsing a JSON request body. The proc is called with the request object, and should probably call halt on the request or raise an exception. |
| :parser |
The parser to use for parsing incoming json. Should be an object that responds to +call(str)+ and returns the parsed data. The default is to call JSON.parse. |
| :include_request |
If true, the parser will be called with the request object as the second argument, so the parser needs to respond to +call(str, request)+. |
| :wrap |
Whether to wrap uploaded JSON data in a hash with a “_json” key. Without this, calls to |
# File lib/roda/plugins/json_parser.rb 50 def self.configure(app, opts=OPTS) 51 app.opts[:json_parser_error_handler] = opts[:error_handler] || app.json_parser_error_handler || DEFAULT_ERROR_HANDLER 52 app.opts[:json_parser_parser] = opts[:parser] || app.json_parser_parser || app.json_parser 53 app.opts[:json_parser_include_request] = opts[:include_request] if opts.has_key?(:include_request) 54 app.opts[:json_parser_content_type_regexp] = opts[:content_type_regexp] || app.json_parser_content_type_regexp 55 56 unless app.json_parser_content_type_regexp 57 # RODA4: Switch to /\Aapplication\/(?:vnd\.api\+)?json\b/i by default 58 RodaPlugins.warn(':content_type_regexp option not provided to json_parser plugin, using /json/ for backwards compatibility, which may be insecure, using /\Aapplication\/json\b/i or /\Aapplication\/(?:vnd\.api\+)?json\b/i is recommended') 59 app.opts[:json_parser_content_type_regexp] = /json/ 60 end 61 62 case opts[:wrap] 63 when :unless_hash, :always 64 app.opts[:json_parser_wrap] = opts[:wrap] 65 when nil 66 # Nothing 67 else 68 raise RodaError, "unsupported option value for json_parser plugin :wrap option: #{opts[:wrap].inspect} (should be :unless_hash or :always)" 69 end 70 end
simplecov:enable
# File lib/roda/plugins/json_parser.rb 23 def self.load_dependencies(app, opts=OPTS) 24 app.plugin :_json 25 end