Class: JSONx
- Inherits:
-
Object
- Object
- JSONx
- Defined in:
- lib/jsonx.rb
Instance Attribute Summary collapse
-
#to_json ⇒ Object
readonly
Returns the value of attribute to_json.
-
#to_s ⇒ Object
readonly
Returns the value of attribute to_s.
Instance Method Summary collapse
-
#initialize(obj) ⇒ JSONx
constructor
A new instance of JSONx.
- #json_to_jsonx(h) ⇒ Object
- #jsonx_to_json(xml) ⇒ Object
Constructor Details
#initialize(obj) ⇒ JSONx
Returns a new instance of JSONx.
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/jsonx.rb', line 13 def initialize(obj) if obj.is_a?(String) then if obj.lstrip[0] == '<' then jsonx_to_json obj else json_to_jsonx JSON.parse(obj) end else json_to_jsonx obj # transform the hash end end |
Instance Attribute Details
#to_json ⇒ Object (readonly)
Returns the value of attribute to_json.
11 12 13 |
# File 'lib/jsonx.rb', line 11 def to_json @to_json end |
#to_s ⇒ Object (readonly)
Returns the value of attribute to_s.
11 12 13 |
# File 'lib/jsonx.rb', line 11 def to_s @to_s end |
Instance Method Details
#json_to_jsonx(h) ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/jsonx.rb', line 30 def json_to_jsonx(h) types = { Hash: ->(k, h){ type = 'json:object' [type, '', (k.empty? ? {} : {name: k}), *h.map {|k2,v| types[v.class.to_s.to_sym].call(k2, v)} ] }, FalseClass: ->(k, b){ ['json:boolean', b.to_s, k.empty? ? {} : {name: k}]}, TrueClass: ->(k, b){ ['json:boolean', b.to_s, k.empty? ? {} : {name: k}]}, Fixnum: ->(k, n){ ['json:number', n, k.empty? ? {} : {name: k}]}, NilClass: ->(k, n){ ['json:null', '', k.empty? ? {} : {name: k}]}, String: ->(k, s){ ['json:string', s, k.empty? ? {} : {name: k}]}, Array: ->(k, a){ ['json:array', '', {name: k}, *a.map{|y| types[y.class.to_s.to_sym].call('', y.to_s)} ] } } a = types[:Hash].call '', h a[2] = {'xsi:schemaLocation' => "http://www.datapower.com/schemas/json jsonx.xsd", 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance", 'xmlns:json' => "http://www.ibm.com/xmlns/prod/2009/jsonx"} @to_s = Rexle.new(a).xml pretty: true end |
#jsonx_to_json(xml) ⇒ Object
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/jsonx.rb', line 59 def jsonx_to_json(xml) doc = Rexle.new xml types = { boolean: ->(e){ e.text.downcase == 'true' }, string: ->(e){e.text}, null: ->(e){nil}, number: ->(e){ s = e.text; s.to_i == s.to_f ? s.to_i : s.to_f}, array: ->(e){ e.elements.map {|x| types[x.name[/\w+$/].to_sym].call x } }, object: ->(e){ e.elements.inject({}) do |r, x| name = x.name[/\w+$/] r.merge(x.attributes[:name] => types[name.to_sym].call(x)) end } } @to_json = types[:object].call doc.root end |