将Ruby哈希转换为哈希数组

时间:2013-10-29 06:28:06

标签: ruby-on-rails ruby json parse-platform

将Ruby Hash转换为以下在 parse.com 中使用的哈希格式:

[{
    "__type": "Pointer",
    "className": "Tag",
    "objectId": "DLAPiFlMYL"
}, {
    "__type": "Pointer",
    "className": "Tag",
    "objectId": "trIItAa4bJ"
}]

输入:

{: __type = > "Pointer",
    : className = > "Tag",
    : objectId = > "DLAPiFlMYL"
}

输出:

[{
    "__type": "Pointer",
    "className": "Tag",
    "objectId": "DLAPiFlMYL"
}]

2 个答案:

答案 0 :(得分:1)

只需使用rails提供的to_json方法

{:__type=>"Pointer",:className=>"Tag",:objectId=>"DLAPiFlMYL"}.to_json

答案 1 :(得分:0)

您可以使用HashWithIndifferentAccess

require 'active_support/hash_with_indifferent_access'
my_hash = {:__type=>"Pointer",:className=>"Tag",:objectId=>"DLAPiFlMYL"}
my_hash = HashWithIndifferentAccess.new my_hash
=> {"__type"=>"Pointer", "className"=>"Tag", "objectId"=>"DLAPiFlMYL"}
> my_hash['className']
=> "Tag"
> my_hash[:className]
=> "Tag"