Skip to content

Instantly share code, notes, and snippets.

@AMHOL
Last active August 29, 2015 14:19
Show Gist options
  • Save AMHOL/f429d9d2cb3eb61bfdbd to your computer and use it in GitHub Desktop.
Save AMHOL/f429d9d2cb3eb61bfdbd to your computer and use it in GitHub Desktop.
require 'transproc/all'
require 'json'
json = <<-EOS
{
"links": {
"self": "http://example.com/posts",
"next": "http://example.com/posts?page[offset]=2",
"last": "http://example.com/posts?page[offset]=10"
},
"data": [{
"type": "posts",
"id": "1",
"title": "JSON API paints my bikeshed!",
"links": {
"self": "http://example.com/posts/1",
"author": {
"self": "http://example.com/posts/1/links/author",
"related": "http://example.com/posts/1/author",
"linkage": { "type": "people", "id": "9" }
},
"comments": {
"self": "http://example.com/posts/1/links/comments",
"related": "http://example.com/posts/1/comments",
"linkage": [
{ "type": "comments", "id": "5" },
{ "type": "comments", "id": "12" }
]
}
}
}],
"included": [{
"type": "people",
"id": "9",
"first-name": "Dan",
"last-name": "Gebhardt",
"twitter": "dgeb",
"links": {
"self": "http://example.com/people/9"
}
}, {
"type": "comments",
"id": "5",
"body": "First!",
"links": {
"self": "http://example.com/comments/5"
}
}, {
"type": "comments",
"id": "12",
"body": "I like XML better",
"links": {
"self": "http://example.com/comments/12"
}
}]
}
EOS
# compose transformation functions
include Transproc::Helper
Transproc.register(:recursive_symbolize_keys, t(:hash_recursion, t(:symbolize_keys)))
transformation = t(:recursive_symbolize_keys) + t(:map_values, t(:is, ::Array, t(:map_array, t(:recursive_symbolize_keys))))
@AMHOL
Copy link
Author

AMHOL commented Apr 14, 2015

pp transformation.call(JSON.parse(json))
{:links=>
  {:self=>"http://example.com/posts",
   :next=>"http://example.com/posts?page[offset]=2",
   :last=>"http://example.com/posts?page[offset]=10"},
 :data=>
  [{:type=>"posts",
    :id=>"1",
    :title=>"JSON API paints my bikeshed!",
    :links=>
     {:self=>"http://example.com/posts/1",
      :author=>
       {:self=>"http://example.com/posts/1/links/author",
        :related=>"http://example.com/posts/1/author",
        :linkage=>{:type=>"people", :id=>"9"}},
      :comments=>
       {:self=>"http://example.com/posts/1/links/comments",
        :related=>"http://example.com/posts/1/comments",
        :linkage=>
         [{"type"=>"comments", "id"=>"5"},
          {"type"=>"comments", "id"=>"12"}]}}}],
 :included=>
  [{:type=>"people",
    :id=>"9",
    :"first-name"=>"Dan",
    :"last-name"=>"Gebhardt",
    :twitter=>"dgeb",
    :links=>{:self=>"http://example.com/people/9"}},
   {:type=>"comments",
    :id=>"5",
    :body=>"First!",
    :links=>{:self=>"http://example.com/comments/5"}},
   {:type=>"comments",
    :id=>"12",
    :body=>"I like XML better",
    :links=>{:self=>"http://example.com/comments/12"}}]}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment