RSSAmplifier

Blog do Tino Gomes · Oct 19, 2019

Converter JSON para um Objeto Ruby

0
Sign in to vote or save

This page cannot be shown here. You can still read it on the original site — the toolbar below keeps your place in the directory.

Quem nunca quis validar um JSON usando as validações do ActiveModel do Rails? Mas transformar um JSON multinível em um objeto Ruby parece ser um passo chato de realizar, né? Bom, hoje eu descobri que não. Exemplo de um JSON bem simples 1 2 3 4 5 6 7 8 9 10 11 12 13 14 { "id" : "740b3e24-8686-48b6-9eb0-1b09d04bf18e" , "name" : "Carl Johnson" , "document" : "12345" , "addresses" : [ { "street" :…

Quem nunca quis validar um JSON usando as validações do ActiveModel do Rails? Mas transformar um JSON multinível em um objeto Ruby parece ser um passo chato de realizar, né? Bom, hoje eu descobri que não.

Exemplo de um JSON bem simples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
  "id": "740b3e24-8686-48b6-9eb0-1b09d04bf18e",
  "name": "Carl Johnson",
  "document": "12345",
  "addresses": [
    {
      "street": "414, East 137th Street",
      "neiborhood": "Compton",
      "city": "Los Angeles",
      "state": "CA",
      "zipcode": "90061"
    }
  ]
}

Importando o JSON para uma classe

1
2
3
4
5
6
7
8
9
10
11
12
13
class AccountFromJson < OpenStruct
  include ActiveModel::Validations
  validates :name, :document, presence: true
end
json = File.read('./any/path/file.json')
account = JSON.parse json, object_class: AccountFromJson
account.valid? # => true
account.name # => "Carl Johnson"
account.addresses[0].street # => "414, East 137th Street"

Ah, e Também funciona se no JSON for um array.

Pois é, quem diz que macaco velho não aprende “novos” truques?

Referências:

Read on blog.tinogomes.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.