牛骨文教育服务平台(让学习变的简单)
博文笔记

ruby中hash转为json

创建时间:2014-10-31 投稿人: 浏览次数:619

该例子中,用正则表达式解析字符串,然后整合成hash数据结构

代码如下:


require "json"

text="cdn-node-12 - 31/Oct/2014:12:26:03 +0000 - x.x.x.20 - GET /lo.mp4?d=1 HTTP/1.1 - 200 - 1406284 - ramfs - 123.299 - -"


REGEXP =/^(?<node>[^ ]*) - (?<time_local>[^ ]* [^ ]*) - (?<remote_addr>[^ ]*) - (?<request>[^ ]* [^ ]* [^ ]*) - (?<status>[^ ]*) - (?<body_bytes_sent>[^ ]*) - (?<cached_method>[^ ]*) - (?<request_time>[^ ]*) - (?<upstream_response_time>[^ ]*)$/


 m = REGEXP.match(text)
unless m
return nil
end

record = {}
m.names.each {|name|
if value = m[name]
record[name]=value
end
}




result = record.to_json


puts result
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。