将json格式的键值对转换为以符号为键的ruby hash的最佳方法是什么? [英] what is the best way to convert a json formatted key value pair to ruby hash with symbol as key?
本文介绍了将json格式的键值对转换为以符号为键的ruby hash的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道将json格式的键值对转换为以符号为键的ruby hash的最佳方法是什么: 例如:
I am wondering what is the best way to convert a json formatted key value pair to ruby hash with symbol as key: example:
{ 'user': { 'name': 'foo', 'age': 40, 'location': { 'city' : 'bar', 'state': 'ca' } } }
==>
{ :user=>{ :name => 'foo', :age =>'40', :location=>{ :city => 'bar', :state=>'ca' } } }
有没有一个辅助方法可以做到这一点?
Is there a helper method can do this?
推荐答案
在解析json字符串时使用json gem可以在symbolize_names选项中传递.参见此处: http://flori.github.com/json/doc/index.html (看一下解析中)
using the json gem when parsing the json string you can pass in the symbolize_names option. See here: http://flori.github.com/json/doc/index.html (look under parse)
例如:
>> s ="{\"akey\":\"one\",\"bkey\":\"two\"}"
>> JSON.parse(s,:symbolize_names => true)
=> {:akey=>"one", :bkey=>"two"}
这篇关于将json格式的键值对转换为以符号为键的ruby hash的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文