正文

Ruby和Ruby on Rails中解析JSON格式数据的实例教程(ruby woo)深度揭秘

文章摘要

这篇文章介绍了在Ruby语言中如何使用JSON进行数据解析,并重点讲解了两种JSON解析方法:一种是不安全的方法,另一种是通过`SafeJSON`模块实现的安全解析方式。文章指出,不安全的方法可能会受到注入攻击的影响,例如直接调用`JSON::parse`方法时,若输入的JSON字符串不加限制,可能会导致安全漏洞。为此,文章介绍了`SafeJSON`模块,该模块通过引入安全的环境来解析JSON字符串,避免潜在的注入攻击。此外,文章还提到在Ruby on Rails中,通过RJS插件可以方便地使用JSON进行数据交换,提供了JSON插件的安装方法和使用示例。文章最后强调了JSON作为数据交换格式的重要性,并提醒在使用JSON解析时需要注意JSON字符串中key是否带引号,以避免解析异常。



Ruby解析JSON

Ruby解析Json例子:
json='[“a”, “B”, “C”]’ puts “Unsafe #{unsafe_json (json).inspect}” #输出Unsafe [“a”, “B”, “C”]

Ruby解析Json把上面的json字符串解析成Array。这样的方法并不安全,比如:

json=’puts “Danger Will Robinson”‘ puts “Unsafe #{unsafe_json (json).inspect}”

又该输出什么呢?很遗憾,解析不出什么东西,跳出一个警告:warning: character class has `[‘ without escape安全的方法如下:

module SafeJSON require ‘monitor’ def SafeJSON.build_safe_json ret=nil waiter=” waiter.extend(MonitorMixin) wait_cond=waiter.new_cond Thread.start do $SAFE=4 ret=Proc.new {|json| eval(json.gsub(/([“‘])/s*:/s* ([‘”0-9tfn/[{])/) end return ret end @@parser=SafeJSON.build_safe_json # Safely parse the JSON input def SafeJSON.parse(input) @@parser.call(input) rescue SecurityError return nil end end

包含这个Module,你就可以这样使用Ruby解析Json:

peoples=SafeJSON.parse(‘ ‘) puts peoples[“peoples”][1][“name”] #输出site120_2

Ruby on Rails中

rails通过RJS内置了对AJAX的支持,也许用到json的机会并不多,不过作为一种数据交换的方便格式,还是值的注意,下面

这里使用到Json插件,安装命令

gem install json_pure

使用例子:

require “open-uri” require ‘json’ def index uri=’*****’ response=nil begin open(uri) do |http| response=http.read end @json=JSON::parse(response) rescue=> text # 异常处理 logger.error(“GetMailListserror=” + text) flash.now[:error]=’获取邮件列表失败。’ end end

这里json解析器需要json格式的key必须带引号,如果没有引号的话会解析出现异常。

您可能感兴趣的文章:使用Ruby来处理JSON的简单教程Ruby中嵌套对象转换成json的方法Ruby解析处理YAML和json格式数据