Max Page
Max Page

Reputation: 33

Change ruby hash to jsonl - JSON seperated by newlines

I am looking at posting to an endpoint on Bubble.io using Ruby and they require jsonl (plain text, new-line seperated) instead of JSON.

Is there a way to take a hash and make it jsonl? Something like hash.to_jsonl.

Upvotes: 1

Views: 1409

Answers (2)

user10617847
user10617847

Reputation: 301

For jsonl (or ndjson), the json need to be formated as single line. Therefor use to_json method.

require 'json'

group = [{:name => "Tom", :age => 27}, {:name => "Jerry", :age => 37}]
puts group.map { |r| JSON.generate(r) }.join("\n")

This code generates the following:

{"name":"Tom","age":27}
{"name":"Jerry","age":37}

Upvotes: 5

Max Page
Max Page

Reputation: 33

Here is the solution I went with:

group = [{name => "Tom"}, {name => "Jerry"}]
generated = []

group.each do |r|
    generated << JSON.generate(r)
end

jsonl_text = generated.join("\n")

Upvotes: 0

Related Questions