Mashie to JSON
title: "Converting `Hashie::Mash`es to JSON on the command-line"
description: "How to convert the string format of a Ruby `Hashie::Mash` to a JSON object, on the command-line."
date: date
syndication:
- "https://brid.gy/publish/twitter"
tags:
- blogumentation
- command-line
- ruby
license_code: "Apache-2.0"
license_prose: "CC-BY-NC-SA-4.0"
slug: "cli-mash-parse"
If you're working with the great Hashie project in Ruby, you may have seen the string representation output in your logs.
It sometimes isn't the most readable/grokable, so you may want to pretty-print them.
For instance, let's take this example:
#<Hashie::Mash birth_date=Thu, 1 Jan 1970" code="test" email="test@test.com" first_name="test">
We can write the following command-line tool, based on this StackOverflow answer:
require 'json'
s = ARGF.read
h = s[/(?<=user=#<Hashie::Mash ).*?(?=>)/].
split(/(?=[\s\A]\S+=)/).
map do |s|
s.
strip.
split('=').
map { |s| s.gsub(/\A"|"\z/, "") }
end.to_h
jj h
Edited by Jamie Tanna