ruby-on-rails - 如何在葡萄实体的响应中修复 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"
}
]
}
]
解决方案
如果credentials
是一个包含 JSON 的字符串,为了让 Grape 将其呈现为 JSON 对象(而不是字符串),您必须对其进行反序列化:
class Entity < Grape::Entity
expose :id
expose :name
expose :credentials
def credentials
JSON.load object.credentials
end
end
推荐阅读
- sendgrid - sendgrid 每个键可以有不同的 requiretls 设置吗?
- ruby-on-rails - 凭证文件未在 Amazon Linux 上读取 Rails 6.1
- javascript - 你如何使用事件委托来切换 Font Awesome 5 SVG 图标?
- java - 如何在 Android JAVA 的列表视图中显示部分但不是全部 JSON 数据
- html - 使用样式组件垂直对齐 div 中的文本
- laravel - Laravel 控制器触发模式以显示数据
- mysql - mysql分区修剪不适用于连接
- python-3.x - 芹菜任务无法使用python从postgresql数据库中迭代多行
- r - 闪亮的输出怪异
- javascript - 单击并显示内容时,使圆形 div 扩展到其父级