gpt4 book ai didi

ruby-on-rails - 哈希 to_json 和返回不保留哈希作为键?

转载 作者:数据小太阳 更新时间:2023-10-29 08:50:55 25 4
gpt4 key购买 nike

还有其他人遇到这个问题吗?

hash_as_key = {'one' => 1, 'two' => 2}
outer_hash = {hash_as_key => 3}

outer_hash.keys[0].class
=> Hash

as_json = outer_hash.to_json
back_to_obj = JSON.parse(as_json)

back_to_obj.keys[0]
=> "{\"one\"=>1, \"two\"=>2}"
back_to_obj.keys[0].class
=> String

如果您有一个 Hash 对象,其中的键是哈希本身,转换为 JSON 并恢复为 Ruby 对象似乎会将键转换为字符串。

最佳答案

keys in JSON objects are strings没有别的:

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

enter image description here

因此,一旦您的数据结构转换为 JSON,您的键就会变成字符串。然后,一旦您的数据采用 JSON,您的 key 的原始类型信息就会丢失。

Ruby 的哈希比 JSON 的对象更加灵活和通用,因此并非每个 Ruby 哈希都可以用 JSON 表示。如果您将 JSON 用于数据存储和传输,那么您必须将数据限制为 JSON 支持的内容,或者将您的数据转换为与 JSON 兼容的结构。

如果您查看中间 JSON,您将看到发生了什么:

> puts outer_hash.to_json
{"{\"one\"=>1, \"two\"=>2}":3}

所以键是字符串 '{"one"=>1, "two"=>2}' 因为这就是 hash_as_key.to_s 给你的。类似地,数字键将被字符串化为 to_s 并失去其“numberness”:

> {1 => 2}.to_json
=> "{\"1\":2}"

关于ruby-on-rails - 哈希 to_json 和返回不保留哈希作为键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13284697/

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