Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For the JSON library to be available, you may have to install <code>libjson-ruby</code> from your package manager.</p> <p>To use the 'json' library:</p> <pre><code>require 'json' </code></pre> <p>To convert an object to JSON (these 3 ways are equivalent):</p> <pre><code>JSON.dump object #returns a JSON string JSON.generate object #returns a JSON string object.to_json #returns a JSON string </code></pre> <p>To convert JSON text to an object (these 2 ways are equivalent):</p> <pre><code>JSON.load string #returns an object JSON.parse string #returns an object </code></pre> <p>It will be a bit more difficult for objects from your own classes. For the following class, to_json will produce something like <code>"\"#&lt;A:0xb76e5728&gt;\""</code>.</p> <pre><code>class A def initialize a=[1,2,3], b='hello' @a = a @b = b end end </code></pre> <p>This probably isn't desirable. To effectively serialise your object as JSON, you should create your own to_json method. To go with this, a from_json class method would be useful. You could extend your class like so:</p> <pre><code>class A def to_json {'a' =&gt; @a, 'b' =&gt; @b}.to_json end def self.from_json string data = JSON.load string self.new data['a'], data['b'] end end </code></pre> <p>You could automate this by inheriting from a 'JSONable' class:</p> <pre><code>class JSONable def to_json hash = {} self.instance_variables.each do |var| hash[var] = self.instance_variable_get var end hash.to_json end def from_json! string JSON.load(string).each do |var, val| self.instance_variable_set var, val end end end </code></pre> <p>Then you can use <code>object.to_json</code> to serialise to JSON and <code>object.from_json! string</code> to copy the saved state that was saved as the JSON string to the object.</p>
    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. 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