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 147 147: def self.db_parse_json(s) 148: parse_json(s) 149: rescue Sequel::InvalidValue 150: raise unless s.is_a?(String) 151: parse_json("[#{s}]").first 152: end
Same as db_parse_json, but consider the input as jsonb.
# File lib/sequel/extensions/pg_json.rb, line 155 155: def self.db_parse_jsonb(s) 156: parse_json(s, true) 157: rescue Sequel::InvalidValue 158: raise unless s.is_a?(String) 159: parse_json("[#{s}]").first 160: end
# File lib/sequel/extensions/pg_json.rb, line 136 136: def self.extended(db) 137: db.instance_eval do 138: copy_conversion_procs([114, 199, 3802, 3807]) 139: @schema_type_classes[:json] = [JSONHash, JSONArray] 140: @schema_type_classes[:jsonb] = [JSONBHash, JSONBArray] 141: end 142: 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 166 166: def self.parse_json(s, jsonb=false) 167: begin 168: value = Sequel.parse_json(s) 169: rescue Sequel.json_parser_error_class => e 170: raise Sequel.convert_exception_class(e, Sequel::InvalidValue) 171: end 172: 173: case value 174: when Array 175: (jsonb ? JSONBArray : JSONArray).new(value) 176: when Hash 177: (jsonb ? JSONBHash : JSONHash).new(value) 178: when String, Numeric, true, false, nil 179: value 180: else 181: raise Sequel::InvalidValue, "unhandled json value: #{value.inspect} (from #{s.inspect})" 182: end 183: end