首页 > 解决方案 > 如何在葡萄实体的响应中修复 JSON 字符串

问题描述

我试图公开一个作为 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"
            }
        ]
    }
]

标签: ruby-on-railsjsongrapegrape-entity

解决方案


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

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

  def credentials
    JSON.load object.credentials
  end
end

推荐阅读