Ruby和Ruby on Rails中解析JSON格式数据的实例教程
前端  /  管理员 发布于 8年前   409
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/[{])/){"#{$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:
peoples=SafeJSON.parse('
{"peoples":[{"name":"site120","
email":"[email protected]","sex":"男"},
{"name":"site120_2","email":"site1
[email protected]_2","sex":"男_2"}]}')
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必须带引号,如果没有引号的话会解析出现异常。
test1 在
opencode + Oh-my-openagent,我的第一个免费的ai编程智能体管家:Sisyphus中评论 test..122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..Zita 在
Google AI Studio升级全栈 vibe coding体验,可直接构建带登录和数据库的应用中评论 111222..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号
