Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Converting the Output to JSON #492

Open
matton2 opened this issue Feb 9, 2024 · 2 comments
Open

Converting the Output to JSON #492

matton2 opened this issue Feb 9, 2024 · 2 comments

Comments

@matton2
Copy link

matton2 commented Feb 9, 2024

Hello! I just started using this package and has been the easiest to connect and faster responses among the others I have tried. I have a requirement to return the Trino results in JSON format. Is there a way to add the columns to each of the results in data?

Go from this
[ [ "data1" ] ]

To this
[ { 'column1': "data1" } ]

@matton2
Copy link
Author

matton2 commented Feb 9, 2024

This is not tested but the code could look something like this:

async JsonFormatting(data:any[] |undefined, columnData:any[] |undefined): Promise<any> {

    const rowData = JSON.parse(JSON.stringify(data, (key, value) => typeof value === 'bigint' ? value.toString:value))
    const genObj: any[] = []
    const obj: any[] = JSON.parse(JSON.stringify(genObj))
    let col = JSON.parse(JSON.stringify(columnData))
    for(let i = 0; i < rowData; i++) {
      const row = rowData[i]
      const jsonRow: any = {}
      for (let j = 0; j < row.length; j++) {
        const colName = col[j]
        jsonRow[colName.name] = row[j]
      }
      obj.push(jsonRow)
    }
    obj
  }

  async queryToJson(query: Query | string): Promise<QueryResult> {
    const req = typeof query === 'string' ? {query} : query;
    const headers: RawAxiosRequestHeaders = {
      [TRINO_USER_HEADER]: req.user,
      [TRINO_CATALOG_HEADER]: req.catalog,
      [TRINO_SCHEMA_HEADER]: req.schema,
      [TRINO_SESSION_HEADER]: encodeAsString(req.session ?? {}),
      [TRINO_EXTRA_CREDENTIAL_HEADER]: encodeAsString(
        req.extraCredential ?? {}
      ),
    };
    const requestConfig = {
      method: 'POST',
      url: '/v1/statement',
      data: req.query,
      headers: cleanHeaders(headers),
    };
    return this.request<QueryResult>(requestConfig).then(
      result => this.JsonFormatting(result.data, result.columns)
      )

  }

@mosabua
Copy link
Member

mosabua commented Nov 17, 2024

Could you send a PR that allows this as an optional setup?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants