Ruby JSON解析修改哈希键 [英] Ruby JSON parse changes Hash keys

查看:110
本文介绍了Ruby JSON解析修改哈希键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有这个哈希:

  {
:info => [
{
:from => Ryan Bates,
:message => sup bra,
:time => 04:35 AM
}
]
}

我可以通过执行 hash [:info]



来调用info数组。现在,当我把它变成JSON JSON.generate),然后解析它(JSON.parse),我得到这个哈希:

  {
info=> [
{
from=> Ryan Bates,
message=> sup bra,
time=> 04:35 AM
}
]
}

现在,如果我使用 hash [:info] ,它会返回 nil ,但如果我使用 hash [info]



这是为什么?无论如何,修复这种不兼容性(除了从一开始就使用字符串键)?

解决方案

总之,没有。以这种方式考虑一下,在JSON中存储符号与在JSON中存储字符串相同。因此,在解析JSON字符串时,您无法区分这两者。您当然可以将字符串键转换回符号,或者实际上甚至可以构建一个类来与JSON进行交互,这会自动执行此操作,但我建议您只使用字符串。



但是,仅仅是为了它,以前就是这个问题的答案:

什么是最好的方式来转换一个JSON格式化的键值对红宝石哈希与符号为关键?



ActiveSupport :: JSON解码哈希丢失符号



或者一个 HashWithIndifferentAccess


Lets say I have this Hash:

{
  :info => [
    {
        :from => "Ryan Bates",
        :message => "sup bra",
        :time => "04:35 AM"
    }
  ]
}

I can call the info array by doing hash[:info].

Now when I turn this into JSON (JSON.generate), and then parse it (JSON.parse), I get this hash:

{
  "info" => [
    {
        "from" => "Ryan Bates",
        "message" => "sup bra",
        "time" => "04:35 AM"
    }
  ]
}

Now if I use hash[:info] it returns nil, but not if I use hash["info"].

Why is this? And is there anyway to fix this incompatibility (besides using string keys from the start)?

解决方案

In short, no. Think about it this way, storing symbols in JSON is the same as storing strings in JSON. So you cannot possibly distinguish between the two when it comes to parsing the JSON string. You can of course convert the string keys back into symbols, or in fact even build a class to interact with JSON which does this automagically, but I would recommend just using strings.

But, just for the sake of it, here are the answers to this question the previous times it's been asked:

what is the best way to convert a json formatted key value pair to ruby hash with symbol as key?

ActiveSupport::JSON decode hash losing symbols

Or perhaps a HashWithIndifferentAccess

这篇关于Ruby JSON解析修改哈希键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆