[LRUG] Serialising a struct

Damon Allen Davison damon at allolex.net
Mon Apr 14 07:53:41 PDT 2014


On Mon, Apr 14, 2014 at 10:07 AM, Stephen Nelson-Smith <sanelson at gmail.com>
 wrote:
>
> What's the best way to make a struct available as canned data?  I can view
> the data I want as a struct using pry... or I can dump the API response
> using VCR, but neither really helps.  The API is actually just XML, and I
> can't work out how to serialise the struct so I can get it back again as a
> struct... Marshal doesn't support dumping from a Struct, JSON gives me a
> string representation, and YAML gives me a Psych::Nodes::Document object...
>
>
I think this will do what you need, if I understood your question correctly:

#!/usr/bin/env ruby
require 'json'
require 'json/add/struct'
require 'awesome_print'

Serial = Struct.new(:foo, :bar, :baz)

s = Serial.new('this','that','the other')
puts 'The Struct instance'
ap s
# {
#     :foo => "this",
#     :bar => "that",
#     :baz => "the other"
# }

serialised = s.as_json
puts 'Serialised'
ap serialised
# {
#     "json_class" => "Serial",
#              "v" => [
#         [0] "this",
#         [1] "that",
#         [2] "the other"
#     ]
# }

json_string = serialised.to_json
puts 'Stringified'
ap json_string
# "{\"json_class\":\"Serial\",\"v\":[\"this\",\"that\",\"the other\"]}"

deserialised = Serial.json_create( JSON.parse(json_string) )
puts 'Deserialised'
ap deserialised
# {
#     :foo => "this",
#     :bar => "that",
#     :baz => "the other"
# }


Warm Regards

-- 

Damon Davison
http://allolex.net
@allolex

You can hire me:
http://curatur.com
@curatur
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20140414/532ea638/attachment.html>


More information about the Chat mailing list