Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data type of JSON field in Postgres

I have a Postgres JSON column where some columns have data like:

{"value":90}
{"value":99.9}

...whereas other columns have data like:

{"value":"A"}
{"value":"B"}

The -> operator (i.e. fields->'value') would cast the value to JSON, whereas the ->> operator (i.e. fields->>'value') casts the value to text, as reported by pg_typeof. Is there a way to find the "actual" data type of a JSON field?

My current approach would be to use Regex to determine whether the occurrence of fields->>'value' in fields::text is surrounded by double quotes.

Is there a better way?

like image 598
Dev Chakraborty Avatar asked Nov 03 '14 07:11

Dev Chakraborty


People also ask

How do I query JSON data type 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.

Is JSON a datatype in PostgreSQL?

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.

How do I query a JSON column in SQL?

To query JSON data, you can use standard T-SQL. If you must create a query or report on JSON data, you can easily convert JSON data to rows and columns by calling the OPENJSON rowset function. For more information, see Convert JSON Data to Rows and Columns with OPENJSON (SQL Server).

What is -> in Postgres?

Postgres offers 2 operators to get a JSON member: the arrow operator: -> returns type JSON or JSONB. the double arrow operator: ->> returns type text.


1 Answers

As @pozs mentioned in comment, from version 9.4 there are available json_typeof(json) and jsonb_typeof(jsonb) functions

Returns the type of the outermost JSON value as a text string. Possible types are object, array, string, number, boolean, and null.

https://www.postgresql.org/docs/current/functions-json.html

Applying to your case, an example of how this could be used for this problem:

SELECT
    json_data.key,
    jsonb_typeof(json_data.value) AS json_data_type,
    COUNT(*) AS occurrences
FROM tablename, jsonb_each(tablename.columnname) AS json_data
GROUP BY 1, 2
ORDER BY 1, 2;
like image 68
Oto Shavadze Avatar answered Sep 17 '22 16:09

Oto Shavadze