rubyでjsonの配列っぽい文字列を配列にする

2017-09-11

上手く説明できないけど、こんなの。

'[
  {
    "sg_message_id":"sendgrid_internal_message_id",
    "email": "john.doe@sendgrid.com",
    "timestamp": 1337197600,
    "smtp-id": "<4FB4041F.6080505@sendgrid.com>",
    "event": "processed"
  },
  {
    "sg_message_id":"sendgrid_internal_message_id",
    "email": "john.doe@sendgrid.com",
    "timestamp": 1337966815,
    "category": "newuser",
    "event": "click",
    "url": "https://sendgrid.com"
  },
  {
    "sg_message_id":"sendgrid_internal_message_id",
    "email": "john.doe@sendgrid.com",
    "timestamp": 1337969592,
    "smtp-id": "<20120525181309.C1A9B40405B3@Example-Mac.local>",
    "event": "group_unsubscribe",
    "asm_group_id": 42
  }
]'

をもごもごする。

require 'json'

data = '[
  {
    "sg_message_id":"sendgrid_internal_message_id",
    "email": "john.doe@sendgrid.com",
    "timestamp": 1337197600,
    "smtp-id": "<4FB4041F.6080505@sendgrid.com>",
    "event": "processed"
  },
  {
    "sg_message_id":"sendgrid_internal_message_id",
    "email": "john.doe@sendgrid.com",
    "timestamp": 1337966815,
    "category": "newuser",
    "event": "click",
    "url": "https://sendgrid.com"
  },
  {
    "sg_message_id":"sendgrid_internal_message_id",
    "email": "john.doe@sendgrid.com",
    "timestamp": 1337969592,
    "smtp-id": "<20120525181309.C1A9B40405B3@Example-Mac.local>",
    "event": "group_unsubscribe",
    "asm_group_id": 42
  }
]'

data_ary = JSON.parse(data)
p data_ary
# => [{"sg_message_id"=>"sendgrid_internal_message_id",
#   "email"=>"john.doe@sendgrid.com",
#   "timestamp"=>1337197600,
#   "smtp-id"=>"<4FB4041F.6080505@sendgrid.com>",
#   "event"=>"processed"},
#  {"sg_message_id"=>"sendgrid_internal_message_id",
#   "email"=>"john.doe@sendgrid.com",
#   "timestamp"=>1337966815,
#   "category"=>"newuser",
#   "event"=>"click",
#   "url"=>"https://sendgrid.com"},
#  {"sg_message_id"=>"sendgrid_internal_message_id",
#   "email"=>"john.doe@sendgrid.com",
#   "timestamp"=>1337969592,
#   "smtp-id"=>"<20120525181309.C1A9B40405B3@Example-Mac.local>",
#   "event"=>"group_unsubscribe",
#   "asm_group_id"=>42}]

p data_ary.class
# => Array

このやり方で合っているのかわからんが。

ちなみに上で使った文字列は↓からお借りした。 https://sendgrid.kke.co.jp/docs/API_Reference/Webhooks/event.html