how to create Json object of each column in a row - json

i have a table itemmaster in Postgresql.
id| attribute1 | attribute2 | attribute3
1 | Good | Average | Best
i want output as json like
[{"attribute1":"Good"},{"attribute2":"Average"},{"attribute3":"Best"}]
i want to use this JSON as nested JSON other object, ihave tried row_to_json and json object builder but not getting exact result.

select json_build_array(json_build_object('attribute1', itemmaster.attribute1),
json_build_object('attribute2', itemmaster.attribute2),
json_build_object('attribute3', itemmaster.attribute3))
from itemmaster;

Related

Convert rows into json object in postgresql

With PostgreSQL 13 I'm trying to convert rows with 2 columns into a JSON object where a column value is the key and the other column is the value.
My table:
key | value
-------- | --------
key1 | value1
key2 | value2
key3 | value3
My expected result:
{"key1":"value1","key2":"value2","key3":"value3"}
I found the json_object function on postgresql website : PostgreSQL JSON functions but I can't get it to work.
I tried with other functions:
SELECT jsonb_agg(jsonb_build_object(key ,value))
FROM mytable
but it gives me an array of json objects
[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"}]
I know I can still build it with string functions but I feel like it's an easy task even if I can't get it :-/
Any help would be appreciated !
You can use jsonb_object_agg()
select jsonb_object_agg(key, value)
from the_table

Count number of objects in JSON array stored as Hive string column

I have a Hive table with a JSON string stored as a string in a column.
Something like this.
Id | Column1 (String)
1 | [{k1:v1,k2:v2},{k3:v3,k4:v4}]
2 | [{k1:v1,k2:v2}]
I want to count the number of JSON objects in the column.
Id | Count
1 | 2
2 | 1
What would be the query to achieve this?
If the JSON objects are such simple structs without nested structs then you can split by '}' and use size()-1:
size(split(column,'[}]'))-1
It works with empty strings correctly, NULLs require special handling if you need to convert to 0:
case when column is null then 0 else size(split(column,'[}]'))-1 end

How to access a field inside a List or Array of JSON Object using SQL query

Consider the following table
+-------------+--------------------------------------------------------------------------+
|company_name | products |
+-------------+--------------------------------------------------------------------------+
| comp1 | [{"name": "prod1","pending": false}, {"name": "prod2","pending": true}] |
+-------------+--------------------------------------------------------------------------+
Suppose I want to retrieve results based on the the value of "name" field inside "products" column, for ex: if "pending" = "true", then display the company_name and also the product name of the particular JSON object inside the List or Array.
Result should look something like,
+-------------+-------------------------------+
|company_name | product_name |
+-------------+-------------------------------+
| comp1 | prod2 |
+-------------+-------------------------------+
You should use a program in python, perl etc that retrieve json and convert it to array and you print the column of array that you need.
use index to get value $[ index ]
Code will be like this:
Select company_name,json_extract(products,'$[1].name') product_name from table where json_extract(products,'$[1].pending')='false' ;
Note: create a dummy table with numbers and join it for index

Using MySQL JSON field to join on a table with custom fields

So I made this system to store custom objects with custom fields for an app that I'm developing. First I have object_def where I save the object definitions:
id | name | fields
------------------------------------------------------------
101 | Group 1 | [{"name": "Title", "id": "AbCdE123"}, ...]
102 | Group 2 | [{"name": "Name", "id": "FgHiJ456"}, ...]
So we have ID (INT), name (VARCHAR) and fields (LONGTEXT). In fields are the object fields like this: {id: string, type: string, name: string}[].
Now In the object table, I have this:
id | object_def_id | object_values
------------------------------------------------------------
235 | 101 | {"AbCdE123": "The Object", ... }
236 | 102 | {"FgHiJ456": "John Perez", ... }
Where object_values is a LONGTEXT also. With that system, I'm able to show the objects on a table in my app using JSON.parse().
Now I've learned that there is a JSON type in MySQL and I want it to use it to do queries and stuff (I'm really new to this).
I've changed the LONGTEXT to JSON and now I wanted to do a SELECT that show the results like this:
#Select objects in group 1:
id | group | Title | ... | other_custom_field
-------------------------------------------------------
235 | Group 1 | The Object | ... | other_custom_value
#Select objects in group 2:
id | group | Name | ... | other_custom_field
-------------------------------------------------------
236 | Group 2 | John Perez | ... | other_custom_value
Id, then group name (I can do this with INNER JOIN) and then all the custom fields with the respective values.
Is this possible? How can I achieve this (hopefully without changing my database structure)? I'm learning MySQL, SQL and databases as I go so I really appreciate your help. Thanks!
Problems I see with your design:
Incorrect JSON format.
[{name: 'Title', id: 'AbCdE123'}, ...]
Should be:
[{"name": "Title", "id": "AbCdE123"}, ...]
You should use the JSON data type instead of LONGTEXT, because JSON will at least reject invalid JSON syntax.
Setting column headings based on data. You can't do this in SQL. Columns and headings must be fixed at the time you prepare the query. You can't do an SQL query that changes its own column headings.
Your object def has an array of attributes, but there's no way in MySQL 5.7 to loop over the "rows" of a JSON array. You'll need to use the JSON_TABLE() in MySQL 8.0.
That will get you closer to being able to look up object values, but then you'll still have to pivot the data into the result set you describe, with one attribute in each column, as if the data had been stored in a traditional way. But SQL doesn't allow you to do dynamic pivoting in a single query. You can't make an SQL query that dynamically grows its own select-list based on the data it finds.
This all makes me wonder...
Why don't you just store the data in the traditional way?
Create a table per object type. Add one column to that table per attribute. That way you get column names. You get column types. You get column constraints — for example, how would you simulate NOT NULL or UNIQUE in your current system?
If you don't want to use SQL, then don't. There are alternatives, like document databases or key/value databases. But don't torture poor SQL by using it to implement an Inner-Platform.

Laravel - Retrive row from DB as json when one column is in json format

I store my data in DB where one of column keep data as a json format.
When I try to retrieve row and response as json then I have that column as a string instead of json object.
DB:
id | name | map_id | map_settings | created_at
1 | Europe | 2 | {"zoom":7,"minZoom":5,"maxZoom":9,"zoomControl":true,"disableDefaultUI":true,"center":"new google.maps.LatLng(51.954422144707960, 19.140930175781250)"} | 2018-08-19 05:19:50
PHP
$mapConfig = MapConfig::with(['places'])->where(['id'=>$id])->get();
return response()->json($mapConfig);
Result
id: 1,
name: "Europe",
map_id: 2,
map_settings: "{\"zoom\":7,\"minZoom\":5,\"maxZoom\":9,\"zoomControl\":true,\"disableDefaultUI\":true,\"center\":\"new google.maps.LatLng(51.954422144707960, 19.140930175781250)\"}"
Why that map_settings is not in correct JSON format? And how to do it?
Thank you.
You have to parse it (map_settings) by json_decode becausue it is a string.
you can use laravel attribute casting and convert your json to array, then it would work fine with response json function.