【问题标题】:How to fix JSON string in the response in Grape Entity如何在葡萄实体的响应中修复 JSON 字符串
【发布时间】:2019-04-18 04:32:06
【问题描述】:

我正在尝试公开一个作为 JSON 字符串保存在数据库中的列。 但它显示为字符串。 任何帮助将不胜感激。

实体样本:

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

实际反应:

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

预期响应:

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

【问题讨论】:

  • 看起来 actual response 实际上只是 json 格式。这些是转义字符 try puts 响应。它将打印您期望的内容。
  • 感谢您的评论!你说的对! @Surya

标签: ruby-on-rails json grape grape-entity


【解决方案1】:

如果credentials 是一个包含 JSON 的字符串,为了让 Grape 将其呈现为 JSON 对象(而不是字符串),您必须对其进行反序列化:

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

  def credentials
    JSON.load object.credentials
  end
end

【讨论】:

    猜你喜欢
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    相关资源
    最近更新 更多