class Grape::Validations::Types::Json

Handles coercion and type checking for parameters that are complex types given as JSON-encoded strings. It accepts both JSON objects and arrays of objects, and will coerce the input to a Hash or Array object respectively. In either case the Grape validation system will apply nested validation rules to all returned objects.

Public Class Methods

parse(input) click to toggle source

Coerce the input into a JSON-like data structure.

@param input [String] a JSON-encoded parameter value @return [Hash,Array<Hash>,nil]

# File lib/grape/validations/types/json.rb, line 20
def parse(input)
  return input if parsed?(input)

  # Allow nulls and blank strings
  return if input.nil? || input.match?(/^\s*$/)

  JSON.parse(input, symbolize_names: true)
end
parsed?(value) click to toggle source

Checks that the input was parsed successfully and isn't something odd such as an array of primitives.

@param value [Object] result of {#parse} @return [true,false]

# File lib/grape/validations/types/json.rb, line 34
def parsed?(value)
  value.is_a?(::Hash) || coerced_collection?(value)
end

Protected Class Methods

coerced_collection?(value) click to toggle source

Is the value an array of JSON-like objects?

@param value [Object] result of {#parse} @return [true,false]

# File lib/grape/validations/types/json.rb, line 44
def coerced_collection?(value)
  value.is_a?(::Array) && value.all?(::Hash)
end