1
2
3
4
5
|
json = '["a", "B", "C"]'
puts "Unsafe #{unsafe_json
(json).inspect}"
#输出Unsafe
[ "a" , "B" , "C" ]
|
Ruby解析Json把上面的json字符串解析成Array。这样的方法并不安全,比如:
1
2
3
4
|
json = 'puts "Danger
Will Robinson"'
puts "Unsafe #{unsafe_json
(json).inspect}"
|
又该输出什么呢?很遗憾,解析不出什么东西,跳出一个警告:warning: character class has `[' without escape安全的方法如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
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/[{])/){" #{$1}=>#{$2}"}) }
waiter.synchronize do wait_cond.signal
end
end
waiter.synchronize do wait_
cond.wait_while { ret. nil ? } 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:
1
2
3
4
5
6
7
|
peoples=SafeJSON.parse('
{ "peoples" :[{ "name" : "site120" ,"
email ":" site120 @163 .com "," sex ":" 男"},
{ "name" : "site120_2" , "email" :"site1
20 @163 .com_2 "," sex ":" 男 _2 "}]}')
puts peoples[ "peoples" ][ 1 ][ "name" ]
#输出site120_2
|
Ruby on Rails中
rails通过RJS内置了对AJAX的支持,也许用到json的机会并不多,不过作为一种数据交换的方便格式,还是值的注意,下面
这里使用到Json插件,安装命令
1
|
gem install json_pure
|
使用例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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必须带引号,如果没有引号的话会解析出现异常。