Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h3>Use Marshal, PStore, or another Ruby solution for non-JSON objects</h3> <p>One might reasonably wonder why a completely reflective language like Ruby doesn't automate JSON generation and parsing of arbitrary classes.</p> <p>However, unless you stick to the JSON types, there is no place to send or receive the JSON objects except to another running Ruby. And in that case, I suspect that the conventional wisdom is "forget JSON, use a native Ruby interface like the core class <code>Marshal</code>. </p> <p>So, if you are really sending those objects to PHP or something non-Ruby, then you should create directly JSON-supported Ruby data structures using Array and the like, and then you will have something that JSON.generate will directly deal with.</p> <p>If you just need serialization it's possible you should use <code>Marshal</code> or <code>PStore</code>.</p> <p>Update: Aha, ok, try this:</p> <pre><code>module AutoJ def auto_j h = {} instance_variables.each do |e| o = instance_variable_get e.to_sym h[e[1..-1]] = (o.respond_to? :auto_j) ? o.auto_j : o; end h end def to_json *a auto_j.to_json *a end end </code></pre> <p>If you then <code>include AutoJ</code> in each of your classes, it should DTRT. In your example this results in</p> <pre><code>{"a":{"string_field1":"aa","string_field2":"bb"},"b":{"int_field3":123,"string_field4":"dd"}} </code></pre> <p>You might want to change the <code>auto_j</code> method to return <code>h.values</code> instead of just <code>h</code>, in which case you get:</p> <pre><code>[["aa","bb"],[123,"dd"]] </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload