0

I'm trying to expose a column which is saved in the DB as a JSON string. But it showed as just string. Any help would be appreciated.

Entity sample:

  class Entity < Grape::Entity
    expose :id
    expose :name
    expose :credentials # this is json string
  end

Actual Response:

[
    {
        "id": 1,
        "name": "Foo",
        "credentials": "[{\"name\":\"key\",\"label\":\"Key\"},{\"name\":\"key2\",\"label\":\"Key2\"}]"
    }
]

Expected Response:

[
    {
        "id": 1,
        "name": "Foo",
        "credentials": [
            {
                "name": "key",
                "label": "Key"
            },
            {
                "name": "key2",
                "label":"Key2"
            }
        ]
    }
]

1 Answers1

1

If credentials is a String containing JSON, in order to have it rendered as JSON object (rather than as String) by Grape, you have to deserialize it:

class Entity < Grape::Entity
  expose :id
  expose :name
  expose :credentials

  def credentials
    JSON.load object.credentials
  end
end
igneus
  • 963
  • 10
  • 25