Module: IMW::Formats::Json
- Defined in:
- lib/imw/formats/json.rb
Overview
Defines methods for reading and writing JSON data.
Instance Method Summary collapse
-
#dump(data, options = {}) ⇒ Object
Dump the
data
into this resource. -
#load(&block) ⇒ Hash, ...
Return the content of this resource.
Instance Method Details
#dump(data, options = {}) ⇒ Object
Dump the data
into this resource. It must be opened for writing.
43 44 45 46 47 48 |
# File 'lib/imw/formats/json.rb', line 43 def dump data, ={} require 'json' write(data.to_json) io.close unless [:persist] self end |
#load(&block) ⇒ Hash, ...
Return the content of this resource.
Will try to be smart about iterating over the data when passed a block.
-
if the outermost JSON data structure is an array, then yield each element
-
if the outermost JSON data structure is a mapping, then yield each key, value pair
-
otherwise just yield the structure
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/imw/formats/json.rb', line 21 def load &block require 'json' json = JSON.parse(read) if block_given? case json when Array json.each { |obj| yield obj } when Hash json.each_pair { |key, value| yield key, value } else yield json end else json end end |