Parsing Encoded JSON Strings on the Command-Line with Ruby

Featured image for sharing metadata for article

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 =
$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

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #command-line #json #ruby.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.