How can I get ruby's JSON to follow object references like Pry/PP? -
i've stared @ long i'm going in circles...
i'm using rbvmomi gem, , in pry, when display object, recurses down thru structure showing me nested objects - to_json seems "dig down" objects, dump reference others> here's example:
[24] pry(main)> g => [guestnicinfo( connected: true, deviceconfigid: 4000, dynamicproperty: [], ipaddress: ["10.102.155.146"], ipconfig: netipconfiginfo( dynamicproperty: [], ipaddress: [netipconfiginfoipaddress( dynamicproperty: [], ipaddress: "10.102.155.146", prefixlength: 20, state: "preferred" )] ), macaddress: "00:50:56:a0:56:9d", network: "f5_real_vm_ips" )] [25] pry(main)> g.to_json => "[\"#<rbvmomi::vim::guestnicinfo:0x000000085ecc68>\"]"
pry apparently uses souped-up pp, , while "pp g" gives me close want, i'm kinda steering hard can toward json don't need custom parser load , manipulate results.
the question - how can json module dig down pp does? , if answer "you can't" - other suggestions achieving goal? i'm not married json - if can data serialized , read later (without writing parse pp output... may exist , should it), it's win.
my "real" goal here slurp bunch of info our vsphere stuff via rbvmomi can network/vm analysis on it, why i'd in nice machine-parsed format. if i'm doing stupid here , there's easier way go - lay on me, i'm not proud. thank time , attention.
update: based on arnie's response, added monkeypatch script:
class rbvmomi::basictypes::dataobject def to_json(*args) h = self.props m = h.merge({ json.create_id => self.class.name }) m.to_json(*args) end end
and to_json recurses down nicely. i'll see submitting (or def, really) project.
the .to_json
works in recursive manner, default behavior defined as:
converts object string (calling to_s), converts json string, , returns result. fallback, if no special method to_json defined object.
json
library has added implementation common classes (check left hand side of this documentation), such array
, range
, datetime
.
for array, to_json
first convert elements json object, concat together, , add array mark [
/]
.
for case, need define customized to_json
method guestnicinfo
, netipconfiginfo
, netipconfiginfoipaddress
. don't know implementation these 3 classes, wrote example demonstrate how achieve this:
require 'json' class myclass attr_accessor :a, :b def initialize(a, b) @a = @b = b end end data = [myclass.new(1, "foobar")] puts data.to_json #=> ["#<myclass:0x007fb6626c7260>"] class myclass def to_json(*args) { json.create_id => self.class.name, :a => a, :b => b }.to_json(*args) end end puts data.to_json #=> [{"json_class":"myclass","a":1,"b":"foobar"}]
Comments
Post a Comment