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 106 106: def self.db_parse_json(s) 107: parse_json(s) 108: rescue Sequel::InvalidValue 109: raise unless s.is_a?(String) 110: parse_json("[#{s}]").first 111: end
# File lib/sequel/extensions/pg_json.rb, line 96 96: def self.extended(db) 97: db.instance_eval do 98: copy_conversion_procs([114, 199]) 99: @schema_type_classes[:json] = [JSONHash, JSONArray] 100: end 101: end
Parse the given string as json, returning either a JSONArray or JSONHash instance, and raising an error if the JSON parsing does not yield an array or hash.
# File lib/sequel/extensions/pg_json.rb, line 116 116: def self.parse_json(s) 117: begin 118: value = Sequel.parse_json(s) 119: rescue Sequel.json_parser_error_class => e 120: raise Sequel.convert_exception_class(e, Sequel::InvalidValue) 121: end 122: 123: case value 124: when Array 125: JSONArray.new(value) 126: when Hash 127: JSONHash.new(value) 128: else 129: raise Sequel::InvalidValue, "unhandled json value: #{value.inspect} (from #{s.inspect})" 130: end 131: end