ruby中hash转为json
该例子中,用正则表达式解析字符串,然后整合成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
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇:没有了
