"" /> "" /> ""/>

Parse popen3 output with some JSON content

23 views Asked by At

I'm pretty new to Ruby and I'm running a command using Open3.popen3() in the following fashion:

_, stdout, stderr, wait_thr = Open3.popen3("<command>")
raise "<command> failed: #{stderr.read}" if wait_thr.value != 0

The expected stdout (stdout.read) follows the next structure (note that the number of elements of the array can vary):

Some log line of plain text:
[{'foo': 'bar', 'fooz': '1'}, {'spam': 'ham', 'eggs': '5'}]

When I read the stdout it returns a String, which of course is the expected class, but I would like to process it a little bit to be able to convert/parse it into JSON. What I tried was:

list = stdout.read.sub! 'Some log line of plain text:', ''
JSON.parse(list)

but it doesn't work:

/Library/Ruby/Gems/2.6.0/gems/json-2.6.1/lib/json/common.rb:216:in `parse': 451: unexpected token at '{'foo': 'bar', 'fooz': '1'}, {'spam': 'ham', 'eggs': '5'}]' (JSON::ParserError)

Is there a way to do it that is not too hacky? TIA!

1

There are 1 answers

0
bert On

Alright, just found a way to do so:

list = stdout.read.sub! 'Some log line of plain text:', ''
JSON.parse(list.gsub('\'', '"'))

Not sure if it's the best way to do it but good enough for me!