assume you have two json lines
{“test” : “value1”}
{“test” : “value2”}
we need the below result
{“test” : “value1”\n"value2"}
how can i achieve this
assume you have two json lines
{“test” : “value1”}
{“test” : “value2”}
we need the below result
{“test” : “value1”\n"value2"}
how can i achieve this
I’m not 100% convinced that either your input or desired output are actually valid JSON. Did you mean
[{"test":"value1"},{"test":"value2"}]
and
[{"test":"value1\nvalue2"}]
instead?
require 'json'
def collapse_tests(json)
json_obj = JSON.parse json
test_values = json_obj.collect { |item| item['test'] }
tests = { 'test': test_values.join("\n") }
tests.to_json
end
sample_input = '[{"test":"value1"}, {"test":"value2"}, {"test":"valuen"}]'
puts collapse_tests sample_input
produces
{"test":"value1\nvalue2\nvaluen"}
You can convert a hash into the desired output with this code:
def merge(*items)
items.flatten.reduce({}) { |hash, a| hash.merge!(a) { |_, y, z| "#{y}\n#{z}" } }
end
p merge({test:1}, {test:2}, {test:3, other_test: 4}) # outputs {:test=>"1\n2\n3", :other_test=>4}
Now, coming to your problem, you have a hash with the content:
{“test” : “value1”}
{“test” : “value2”}
Which is obviously invalid in JSON format, but if you have the code wrapped in an array:
[
{"test":"value1"},
{"test":"value2"}
]
Will make it valid, now just use this code:
#!/usr/bin/ruby -w
def merge(*items)
items.flatten.reduce({}) { |hash, a| hash.merge!(a) { |_, y, z| "#{y}\n#{z}" } }
end
json = %Q<[
{"test":"value1"},
{"test":"value2"}
]>
require 'json'
p merge JSON.parse(json) # outputs {"test"=>"value1\nvalue2"}
thnak you so much,it helped me lot
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs