Module: JSONL
- Defined in:
- lib/jsonl.rb,
lib/jsonl/version.rb
Constant Summary collapse
- VERSION =
'0.1.5'
Class Method Summary collapse
-
.generate(objs, opts = nil) ⇒ Object
Generate a string formatted as JSONL from an array.
-
.parse(source, opts = {}) ⇒ Object
Parse JSONL string and return as an array.
Class Method Details
.generate(objs, opts = nil) ⇒ Object
Generate a string formatted as JSONL from an array.
Attributes
-
objs
- an array consists of objects -
opts
- options passes to ‘JSON.generate`
Exapmles
users = User.all.map(&:attributes) #=> [{"id"=>1, "name"=>"Gilbert", ...}, {"id"=>2, "name"=>"Alexa", ...}, ...]
generated = JSONL.generate(users)
19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/jsonl.rb', line 19 def generate(objs, opts = nil) unless objs.is_a?(Array) raise TypeError, "can't generate from #{objs.class}" end generated = [] objs.map do |obj| generated << JSON.generate(obj, opts) end generated.join("\n") end |
.parse(source, opts = {}) ⇒ Object
Parse JSONL string and return as an array.
Attributes
-
source
- a string formatted as JSONL -
opts
- options passes to ‘JSON.parse`
Examples
source = File.read('source.jsonl')
parsed = JSONL.parse(source)
43 44 45 46 47 48 49 |
# File 'lib/jsonl.rb', line 43 def parse(source, opts = {}) parsed = [] source.each_line do |line| parsed << JSON.parse(line, opts) end parsed end |