Skip to main content

Command Palette

Search for a command to run...

Jsonify Ruby Hash string

Published
1 min read

Sometimes I have this issue of parsing JSON that contains the string representation of Ruby hash for whatever reason.

Problem

It happens obviously because the hash string is not JSON.

require 'json'
hsh_as_str = '{"order_id"=>nil}'
JSON.parse(hsh_as_str)
# JSON::ParserError: 783: unexpected token at '{"order_id"=>nil}'

Solution A

require 'json'
hsh_as_str = '{"order_id"=>nil}'
valid_json = hsh_as_str.gsub('=>', ':').gsub(':nil', ':null')
#=> "{\"order_id\":null}"
JSON.parse(valid_json)
#=> {"order_id"=>nil}

Solution B

require 'json'
hsh_as_str = '{"order_id"=>nil}'
eval(hsh_as_str)
#=> {"order_id"=>nil}

Pitfalls

  • It can be more complicated when the string contains the string representation of Ruby objects, for example:
'{"user"=>#<User id=123>}'

That's it.

Resources

  • https://stackoverflow.com/questions/1667630/how-do-i-convert-a-string-object-into-a-hash-object

More from this blog

Raspberry Pi TensorFlow Liteで物体検出を楽しむ

この記事について Raspberry Pi、TensorFlow、Pythonのいずれにも詳しくない筆者が、物体検出をやって楽しんだ成果の記録です。 TensorFlow公式の物体検出のサンプルプログラムを実行します。 動作環境 ボード Raspberry Pi 4 Model B OS Raspberry Pi OS (32-bit または 64-bit) デスクトップ環境 カメラ Raspberry Pi カメラモジュール v2 Python Python ...

Apr 23, 20231 min read

Elixir Circuits.I2C with Mox

This is written in Japanese. I might convert it to English later, maybe. はじめに Elixirのテストでモックを用意するときに利用するElixirパッケージとして、moxが人気です。Elixir作者のJosé Valimさんが作ったからということもありますが、ただモックを用意するだけではなくElixirアプリの構成をより良くするためのアイデアにまで言及されているので、教科書のようなものと思っています。 一言でいうと「その場...

Dec 3, 20213 min read
M

Masatoshi Nishiguchi's Blog

62 posts

Jsonify Ruby Hash string