0

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!

bert
  • 372
  • 4
  • 13
  • 1
    Strings in JSON must be delimited by a double-quote character `"`, not a single-quote character `'`. As such, what you have there is not JSON but some other format. Check the documentation of the program you are calling to find the actual format of its output. – Holger Just May 04 '23 at 09:01
  • @HolgerJust you are right! I have just find&replaced single quotes by double quotes and now it seems to be working. – bert May 04 '23 at 09:02

1 Answers1

0

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!

bert
  • 372
  • 4
  • 13