# How to serialize/deserialize String to JSON?

**URL:** <https://discourse.rom-rb.org/t/how-to-serialize-deserialize-string-to-json/87>\
**Category:** Uncategorized\
**Created:** [September 27, 2016, 1:02pm UTC](https://discourse.rom-rb.org/t/how-to-serialize-deserialize-string-to-json/87 "2016-09-27T13:02:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dmgr](https://avatars.discourse-cdn.com/v4/letter/d/ecd19e/32.png) [@dmgr](https://discourse.rom-rb.org/u/dmgr)\
**Post date:** [September 27, 2016, 1:02pm UTC](https://discourse.rom-rb.org/t/how-to-serialize-deserialize-string-to-json/87/1 "2016-09-27T13:02:11Z")

</div>

I try to have a table with users and meta column which will be a hash serialized to JSON string:

```
require 'rom-repository'
require 'rom-sql'
require 'dry-struct'

module Relations
  class Users < ROM::Relation[:sql]
    schema :users do
      attribute :meta, Dry::Types['json.hash']
    end

    def by_id(id)
      where(id: id)
    end
  end
end

module Repositories
  class Users < ROM::Repository[:users]
    def [](id)
      users.by_id(id).as(User).one!
    end
  end
end

class User < Dry::Struct
  attribute :meta, Dry::Types['hash'] # Dry::Types['json.hash']
end

container = ROM.container(:sql, 'sqlite:memory') do |config|
  config.register_relation Relations::Users
end

container.gateways[:default].tap do |gateway|
  migration = gateway.migration do
    change do
      create_table :users do
        primary_key :id
        string :name, null: false
        string :meta, null: false, default: '{}'
      end
    end
  end

  migration.apply gateway.connection, :up
end

connection = container.gateways[:default].connection
connection.execute "INSERT INTO users (name, meta) VALUES ('dave', '{admin: true}')"

repo = Repositories::Users.new(container)
p repo.users.as(User).first.meta # returns "{admin: true}", not a Hash

```

I am not sure which type to use to make it works.

---

<div class="post-metadata">

**Author:** ![solnic](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.rom-rb.org/solnic/32/279_2.png) [@solnic](https://discourse.rom-rb.org/u/solnic)\
**Post date:** [October 1, 2016, 5:38am UTC](https://discourse.rom-rb.org/t/how-to-serialize-deserialize-string-to-json/87/2 "2016-10-01T05:38:29Z")

</div>

You could use something like this in the schema:

```ruby
JSONString = Types::String.constructor(&JSON.method(:dump))

```

And then in your struct something like this:

```ruby
JSON = Types::Hash.constructor(&:JSON.method(:load))

```

You could also define a hash schema for your json and use `symbolized` hash schema ie:

```ruby
JSON = Types::Hash
  .symbolized(foo: Types::String, bar: Types::Int)
  .constructor(&:JSON.method(:load))

```
