5

If I have a data in a table as follows

WITH dataset AS (
  SELECT ARRAY[
    CAST(ROW('Bob', 38) AS ROW(name VARCHAR, age INTEGER)),
    CAST(ROW('Alice', 35) AS ROW(name VARCHAR, age INTEGER)),
    CAST(ROW('Jane', 27) AS ROW(name VARCHAR, age INTEGER))
  ] AS users,
  CAST(ROW('Google') AS ROW(company VARCHAR)) AS company
)
SELECT * FROM dataset

Expected format is as follows:

{
    "company": "Google",
    "users": [
        {
            "name": "Bob",
            "age": 38
        },
        {
            "name": "Alice",
            "age": 35
        },
        {
            "name": "Jane",
            "age": 27
        }

    ]
}

How do I a construct a JSON extracted from this data?

3
  • what format do you get back when you run the query exactly?
    – Itay
    Sep 30, 2020 at 18:21
  • I get the top level columns such as company, users but no information about the nested keys such as name,age
    – Ram
    Oct 1, 2020 at 4:24
  • The columns return from prestodb python client are as follows: [('users', 'array(row(name varchar, age integer))', None, None, None, None, None), ('company', 'row(company varchar)', None, None, None, None, None)] I am not sure how to process the nested row
    – Ram
    Oct 1, 2020 at 17:08

1 Answer 1

1

You can just cast it to JSON.

...
SELECT cast(users as json), cast(company as json) FROM dataset

https://trino.io/docs/0.172/functions/json.html

If it doesn't return expected output, please share your expected result.

1
  • 2
    Yeah, it returns as a JSON but without the column/field names.Let me add what i expect as a result.
    – Ram
    Sep 29, 2020 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.