gpt4 book ai didi

mysql - 将 Active Record 对象和字符串属性转换为 JSON

转载 作者:行者123 更新时间:2023-11-29 12:24:44 24 4
gpt4 key购买 nike

我正在尝试将 Rails 记录转换为完全可通过 Javascript 遍历的 JSON 对象。我可以将基本记录转换为 JSON,也可以将每个单独的属性转换为 JSON。但是,我没有一个好的方法将整个对象转换为可遍历的 JSON 对象。理想情况下,解决方案不会涉及迭代每个属性并将值转换为 JSON。如何将整个记录完全转换为可以在 Javascript 中完全遍历的 JSON 格式?

以下是重现我的问题所需执行的步骤。提前致谢。

# database
MySQL, and the column is a Rails text data type.

# seeds.rb
ModelName.create(
has_hash_value: { one: { two: { three: "content"} } }
)

# console
$ rake db:seed

# controller
@resource = ModelName.first.to_json

# erb view
<div id="data" data-json="<$= @resource %>"></div>

# generated HTML
{"has_hash_value":"{:one=\u003e{:two=\u003e{:three=\u003e\"content\"}}}",

# javascript
window.data = $('#data').data().json

# browser console
> data.has_hash_value
< "{:one=>{:two=>{:three=>"content"}}}"
> data.has_hash_value.one
< undefined

更新

我尝试过@resource = JSON.parse(ModelName.first.to_json),但返回的是一个完全不可遍历的字符串。然而,嵌套哈希的格式更好。

# controller
@resource = JSON.parse(ModelName.first.to_json)

# generated HTML
data-json="{"has_hash_value"=>"{:one=>{:two=>{:three=>\"content\"}}}"

# browser console
> data.has_hash_value
< undefined

更新2

当我使用字符串或 json 格式的数据作为种子,并在 Controller 中转换为哈希然后 JSON 时,生成的 HTML 和 JS 响应更清晰,但我仍然无法完全遍历。

# seeds.rb
has_hash_value: { one: { two: { three: "content"} } }.to_json

# controller
@resource = TourAnalytic.first.as_json.to_json

# generated HTML
data-json="{"has_hash_value":"{\"one\":{\"two\":{\"three\":\"content\"}}}"

# browser console
> data.has_hash_value
< Object {has_hash_value: "{"one":{"two":{"three":"content"}}}"}
> data.has_hash_value.one
< undefined

最佳答案

问题在于has_hash_value的值。这是一个字符串(用“s”包裹)。这就是我所做的:

your_hash = { has_hash_value: { one: { two: { three: "content"} } }.to_json }
your_hash[:has_hash_value] = JSON.parse(your_hash[:has_hash_value]

您的哈希值将具有以下值:

{:has_hash_value=>{"一"=>{"二"=>{"三"=>"内容"}}}}

强烈建议将所有这些代码移至模型并覆盖#to_json 方法。

关于mysql - 将 Active Record 对象和字符串属性转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28504200/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com