Marcelo Alves

JSON.parse with object_class

Introduction

user

Marcelo Alves

Web developer living in Central California. Working with Ruby/Rails, Javascript, and dabbling in Elixir. Always searching for solutions that need problems.


notes ruby

JSON.parse with object_class

Posted by Marcelo Alves on .
Featured

notes ruby

JSON.parse with object_class

Posted by Marcelo Alves on .

You can pass an object_class to JSON.parse which will use that class to create an object. Can pass OpenStruct to create a simple object or something like an ActiveRecord class.

json_data = '{"id": 1,"name": "A green door","price": 12.50,"tags": ["home", "green"]}'

parsed_json = JSON.parse(json_data, object_class: OpenStruct)

p parsed_json.name
# "A green door"
user

Marcelo Alves

http://marceloalves.com

Web developer living in Central California. Working with Ruby/Rails, Javascript, and dabbling in Elixir. Always searching for solutions that need problems.