简体   繁体   English

如何在ruby中将ruby格式的json字符串转换为json哈希?

[英]How to convert ruby formatted json string to json hash in ruby?

I want to access json string like hash object so that i can access json using key value like temp["anykey"] . 我想访问类似哈希对象的json字符串,以便我可以使用像temp["anykey"]这样的键值来访问json。 How to convert ruby formatted json string into json object? 如何将ruby格式的json字符串转换为json对象?

I have following json string 我有以下json字符串

temp = '{"accept"=>"*/*", "host"=>"localhost:4567", "version"=>"HTTP/1.1", 
       "user_agent"=>"curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3", 
       "http_token"=>"375fe428b1d32787864264b830c54b97"}'

Do you know about JSON.parse ? 你知道JSON.parse吗?

require 'json'

my_hash = JSON.parse('{"hello": "goodbye"}')
puts my_hash["hello"] => "goodbye"

if your parse this string to ruby object, it will return a ruby Hash object, you can get it like this You can install the json gem for Ruby 如果您将此字符串解析为ruby对象,它将返回一个ruby Hash对象,您可以像这样得到它您可以为Ruby安装json gem

gem install json

You would require the gem in your code like this: 您需要在代码中使用gem,如下所示:

require 'rubygems'
require 'json'

Then you can parse your JSON string like this: 然后你可以像这样解析你的JSON字符串:

ruby_obj = JSON.parse(json_string)

There are also other implementations of JSON for Ruby: 还有其他JSON for Ruby实现:

You can try eval method on temp json string 您可以在temp json字符串上尝试eval方法

Example: 例:

eval(temp)

This will return following hash 这将返回以下哈希值

{"accept"=>"*/*", "host"=>"localhost:4567", "version"=>"HTTP/1.1", "user_agent"=>"curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3", "http_token"=>"375fe428b1d32787864264b830c54b97"}

Hope this will help. 希望这会有所帮助。

Thanks 谢谢

To convert a Ruby hash to json string, simply call to_json. 要将Ruby哈希转换为json字符串,只需调用to_json即可。

require 'json'

temp = {"accept"=>"*/*", "host"=>"localhost:4567", "version"=>"HTTP/1.1", 
   "user_agent"=>"curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3", 
   "http_token"=>"375fe428b1d32787864264b830c54b97"}
temp.to_json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM