JSON.parse 更改排序 - Ruby
在下面的代码中,我的项目的顺序在 JSON.parse(f) 行之后发生更改,即此哈希:
{ 一个=>阿瓦尔, b => bval, c => cval, d =>德瓦尔 }
变成类似:
{ b => bval, c => cval, 一个=>阿瓦尔, d =>德瓦尔 这
是一个问题,因为我的显示代码只是从 json 文件中读取,所以每当我保存回它,然后显示时,所有内容都会发生变化。我可以采取什么措施来保留订单吗?
代码:
f = File.read($PLAN_DESC_PATH)
puts ("f " + f.to_s())
hash = JSON.parse(f)
puts ("hash " + hash.to_s())
我的 Ruby 版本是 1.8.7。我正在使用西纳特拉。我相信我从这里得到了 JSON gem: http://flori.github.com/json/ (抱歉,对此有点陌生)。谢谢!
In the code below, the order of my items gets changed after the JSON.parse(f) line, i.e., this hash:
{
a => aval,
b => bval,
c => cval,
d => dval
}
becomes something like:
{
b => bval,
c => cval,
a => aval,
d => dval
}
This is a problem because my display code just reads from the json file, so any time I save back to it, and then display, everything gets changed around. Is there anything I can do to retain the order?
CODE:
f = File.read($PLAN_DESC_PATH)
puts ("f " + f.to_s())
hash = JSON.parse(f)
puts ("hash " + hash.to_s())
My Ruby version is 1.8.7. I am using Sinatra. I believe I got the JSON gem from here: http://flori.github.com/json/ (sorry, kinda new to this). Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Ruby 1.8.7 中,Hash 类不通过键或添加的顺序来维护顺序。如果你需要类似的东西,你需要实现类似 ActiveSupport::OrderedHash (http://rubydoc.info/docs/rails/ActiveSupport/OrderedHash)
在 Ruby 1.9.x 中,哈希值默认按照插入时排序(参见http://www.ruby-doc.org/core/classes/Hash .html)
当您将哈希序列化为 JSON 时,维护密钥顺序的所有赌注都将被取消。如果您有必要,在序列化后您将需要进行一些后处理以确保顺序。
In Ruby 1.8.7 the Hash class does not maintain order either by keys or by order added. If you need something like that, you would need to implement something like ActiveSupport::OrderedHash (http://rubydoc.info/docs/rails/ActiveSupport/OrderedHash)
In Ruby 1.9.x hashes are ordered by when they are inserted by default (see http://www.ruby-doc.org/core/classes/Hash.html)
When you serialize a hash to JSON, all bets are off for maintaining order of your keys. You'll need some post processing after your serialization to ensure order if that's necessary for you.
不,哈希图并不意味着具有特定的顺序。如果您需要排序,请使用不同的东西,例如数组。或者提取所有键,按照您想要的方式对它们进行排序,然后您就可以得到您喜欢的顺序。
无论如何,你不应该依赖对地图内的排序进行假设,这就是事实。
一个好的选择是:
No, hashmaps are not meant to have a specific ordering. If you need ordering use something different like an array. Or extract all the keys, sort them like you want and then you can have what order you like.
Making assumptions on ordering inside maps is anyway something on which you shouldn't rely, that's the fact.
A good alternative would be to have:
Jack 回答了 Ruby,所以我回答了 JSON。来自 RFC 4627(添加了强调):
“对象是无序的 零个或多个名称/值对的集合”
Jack answered for Ruby, so I'll answer for JSON. From RFC 4627 (emphasis added):
"An object is an unordered collection of zero or more name/value pairs"