diff options
Diffstat (limited to 'lib/json/pure/generator.rb')
-rw-r--r-- | lib/json/pure/generator.rb | 19 |
1 files changed, 17 insertions, 2 deletions
diff --git a/lib/json/pure/generator.rb b/lib/json/pure/generator.rb index 3687e30..7c9b2ad 100644 --- a/lib/json/pure/generator.rb +++ b/lib/json/pure/generator.rb @@ -133,6 +133,8 @@ module JSON # * *allow_nan*: true if NaN, Infinity, and -Infinity should be # generated, otherwise an exception is thrown, if these values are # encountered. This options defaults to false. + # * *quirks_mode*: Enables quirks_mode for parser, that is for example + # generating single JSON values instead of documents is possible. def initialize(opts = {}) @indent = '' @space = '' @@ -141,6 +143,7 @@ module JSON @array_nl = '' @allow_nan = false @ascii_only = false + @quirks_mode = false configure opts end @@ -165,6 +168,10 @@ module JSON # the generated JSON, max_nesting = 0 if no maximum is checked. attr_accessor :max_nesting + # If this attribute is set to true, quirks mode is enabled, otherwise + # it's disabled. + attr_accessor :quirks_mode + # This integer returns the current depth data structure nesting in the # generated JSON. attr_accessor :depth @@ -188,10 +195,17 @@ module JSON @allow_nan end + # Returns true, if only ASCII characters should be generated. Otherwise + # returns false. def ascii_only? @ascii_only end + # Returns true, if quirks mode is enabled. Otherwise returns false. + def quirks_mode? + @quirks_mode + end + # Configure this State instance with the Hash _opts_, and return # itself. def configure(opts) @@ -203,6 +217,7 @@ module JSON @allow_nan = !!opts[:allow_nan] if opts.key?(:allow_nan) @ascii_only = opts[:ascii_only] if opts.key?(:ascii_only) @depth = opts[:depth] || 0 + @quirks_mode = opts[:quirks_mode] if opts.key?(:quirks_mode) if !opts.key?(:max_nesting) # defaults to 19 @max_nesting = 19 elsif opts[:max_nesting] @@ -218,7 +233,7 @@ module JSON # passed to the configure method. def to_h result = {} - for iv in %w[indent space space_before object_nl array_nl allow_nan max_nesting ascii_only depth] + for iv in %w[indent space space_before object_nl array_nl allow_nan max_nesting ascii_only quirks_mode depth] result[iv.intern] = instance_variable_get("@#{iv}") end result @@ -229,7 +244,7 @@ module JSON # GeneratorError exception. def generate(obj) result = obj.to_json(self) - if result !~ /\A\s*(?:\[.*\]|\{.*\})\s*\Z/m + if !@quirks_mode && result !~ /\A\s*(?:\[.*\]|\{.*\})\s*\Z/m raise GeneratorError, "only generation of JSON objects or arrays allowed" end result |