使用JSON.parse转换为Ruby Hash的JSON对象中的键顺序 [英] Order of keys in a JSON object converted to a Ruby Hash with JSON.parse

查看:83
本文介绍了使用JSON.parse转换为Ruby Hash的JSON对象中的键顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,对象键不排序,而在Ruby中,哈希枚举其键值以插入相应键的顺序.

In Javascript, object keys are not ordered, whereas in Ruby, Hashes enumerate their values in the order that the corresponding keys were inserted.

实际上,在将JSON对象转换为Ruby哈希时,Ruby Hash中的键似乎是按照它们在JSON数据中写入的顺序排列的,例如:

In practice, it seems to be the case that when converting JSON objects to Ruby Hashes, keys in the Ruby Hash are in the order in which they were written in the JSON data, e.g.:

irb(main):002:0> JSON.parse('{"a": 1, "b": 2}')
=> {"a"=>1, "b"=>2}

irb(main):005:0> JSON.parse('{"b": 1, "a": 2}')
=> {"b"=>1, "a"=>2}

我可以依靠这样的假设吗?

Can I rely on the assumption that it will always be the case?

我会这样想,因为解析JSON时,我猜解析器会在发现键时插入它们,但是我找不到关于该主题的任何引用.

I'd think so, because when parsing JSON, I guess the parser is inserting keys as it discovers them, but I couldn't find any reference on the subject.

推荐答案

至少在较新版本的Ruby中,基于插入保留键顺序.来自 Ruby 2.6.3 Hash文档

The key order is preserved, based on insert, at least in newer versions of Ruby. From the Ruby 2.6.3 Hash documentation

哈希按插入相应键的顺序枚举其值

Hashes enumerate their values in the order that the corresponding keys were inserted

(据我所知)所有当前受支持的Ruby版本都是这种情况(甚至不支持的旧版2.x版本也如上所述)

This is the case for (as far as I can tell) all currently supported Ruby versions (even older 2.x versions that are unsupported are documented as above)

这篇关于使用JSON.parse转换为Ruby Hash的JSON对象中的键顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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