| Module | Sequel::Postgres::JSONDatabaseMethods |
| In: |
lib/sequel/extensions/pg_json.rb
|
Methods enabling Database object integration with the json type.
Parse JSON data coming from the database. Since PostgreSQL allows non JSON data in JSON fields (such as plain numbers and strings), we don‘t want to raise an exception for that.
# File lib/sequel/extensions/pg_json.rb, line 145
145: def self.db_parse_json(s)
146: parse_json(s)
147: rescue Sequel::InvalidValue
148: raise unless s.is_a?(String)
149: parse_json("[#{s}]").first
150: end
Same as db_parse_json, but consider the input as jsonb.
# File lib/sequel/extensions/pg_json.rb, line 153
153: def self.db_parse_jsonb(s)
154: parse_json(s, true)
155: rescue Sequel::InvalidValue
156: raise unless s.is_a?(String)
157: parse_json("[#{s}]").first
158: end
# File lib/sequel/extensions/pg_json.rb, line 129
129: def self.extended(db)
130: db.instance_exec do
131: add_conversion_proc(114, JSONDatabaseMethods.method(:db_parse_json))
132: add_conversion_proc(3802, JSONDatabaseMethods.method(:db_parse_jsonb))
133: if respond_to?(:register_array_type)
134: register_array_type('json', :oid=>199, :scalar_oid=>114)
135: register_array_type('jsonb', :oid=>3807, :scalar_oid=>3802)
136: end
137: @schema_type_classes[:json] = [JSONHash, JSONArray]
138: @schema_type_classes[:jsonb] = [JSONBHash, JSONBArray]
139: end
140: end
Parse the given string as json, returning either a JSONArray or JSONHash instance (or JSONBArray or JSONBHash instance if jsonb argument is true), or a String, Numeric, true, false, or nil if the json library used supports that.
# File lib/sequel/extensions/pg_json.rb, line 164
164: def self.parse_json(s, jsonb=false)
165: begin
166: value = Sequel.parse_json(s)
167: rescue Sequel.json_parser_error_class => e
168: raise Sequel.convert_exception_class(e, Sequel::InvalidValue)
169: end
170:
171: case value
172: when Array
173: (jsonb ? JSONBArray : JSONArray).new(value)
174: when Hash
175: (jsonb ? JSONBHash : JSONHash).new(value)
176: when String, Numeric, true, false, nil
177: value
178: else
179: raise Sequel::InvalidValue, "unhandled json value: #{value.inspect} (from #{s.inspect})"
180: end
181: end