Parsing Encoded JSON Strings on the Command-Line with Ruby
JSON is a pretty common format for serialising of data, and can either be transmitted as the object itself, or as a string that's encoded the JSON structure.
Although I like to work with APIs or data that just produces the object itself, there are times that you work with things that produce i.e.:
{
"internalResponse": "{\"response\": {\"value\": \"the-thing\"}}"
}
To parse this, you could do something funky with replacing the quotes that are within the body of that field, but then you may have to deal with escaped quotes, and we really should avoid funky code like that.
Fortunately, we can create a small script, which needs to safely parse the string that's provided, as we need Ruby to parse the string and remove the escaped quotes itself:
#!/usr/bin/env ruby
require 'json'
input = ARGF.read
# https://nts.strzibny.name/safe-code-evaluation-in-ruby-with-safe/
$SAFE = 4
input = eval input
jj JSON.parse(input)
This allows us to run the following, based on a file, or stdin:
$ cat file.json
"{\"response\": {\"value\": \"the-thing\"}}"
$ ruby j.rb file.json
$ echo "{\"response\": {\"value\": \"the-thing\"}}" | ruby j.rb