Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use json_populate_recordset in a case-insensitive way

Is it possible to use json_populate_recordset so that the table column names/json keys are compared in an case-insensitive way, using PostgreSQL (9.6)?

For example, the following snippet would return zero row.

CREATE TABLE foo (bar TEXT);
SELECT * from json_populate_recordset(null::foo, '[{"bAr":1}]')

Of course I could transform json keys to lowercase or the table name could be case sensitive.

like image 607
Pier-Alexandre Bouchard Avatar asked Dec 05 '16 03:12

Pier-Alexandre Bouchard


People also ask

What is Json_populate_recordset?

json_populate_recordset(base anyelement, from_json json) jsonb_populate_recordset(base anyelement, from_json jsonb) setof anyelement. Expands the outermost array of objects in from_json to a set of rows whose columns match the record type defined by base (see note below).

How do I query JSON data in PostgreSQL?

Querying the JSON documentPostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.

Does Postgres support JSON?

PostgreSQL offers two types for storing JSON data: json and jsonb . To implement efficient query mechanisms for these data types, PostgreSQL also provides the jsonpath data type described in Section 8.14. 7. The json and jsonb data types accept almost identical sets of values as input.


1 Answers

I don't believe case-insensitive is possible. If you know in advance the case that will be used for records (e.g. they are always camel cased) you can specify a specific case by quoting the column name.

Baseline example to show case-insensitivity:

# create type x as (abc integer);
CREATE TYPE
# select * from json_populate_recordset(null::x, '[{"abc" : 1}, {"Abc" : 2}, {"aBc" : 3}, {"abC" : 4}]');
 abc
-----
   1



(4 rows)

Now let's choose a specific case we want to use by quoting the column name.

# drop type x;
DROP TYPE
# create type x as ("aBc" integer);
CREATE TYPE
edgar=# select * from json_populate_recordset(null::x, '[{"abc" : 1}, {"Abc" : 2}, {"aBc" : 3}, {"abC" : 4}]');
 aBc
-----


   3

(4 rows)

If you can't guarantee the case of your input data you show lower-case everything.

like image 154
Carter Shanklin Avatar answered Oct 16 '22 18:10

Carter Shanklin