Skip to content

Hard to return preformatted json with application/json content-type #1989

Closed
@iabdulin

Description

@iabdulin

For example, we have the following endpoint, returning preformatted json (I return json right from the database)

get 'all_json' do
   {key: 123}.to_json
end

Here's what will be returned:
"{\"key\":123}" with application/json content-type
Grape applies additional .to_json call.

Now let's try to fix this problem, taking into assumption that I already have a prebuilt JSON in my endpoint.

Options:

  1. Adding env['api.format'] = :binary or :txt{"key":123} but empty content-type

  2. Adding content_type 'application/json' or header 'Content-Type', 'application/json' to :txt or :binary format — "{\"key\":123}"

The only way I was able to solve this is by overwriting :json formatter with:

formatter :json, ->(object, env) {
      if object.is_a?(String)
        object
      else
        return object.to_json if object.respond_to?(:to_json)
        Grape::Json.dump(object)
      end
    }

Maybe there's another way?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions