Converte o tipo complexo especificado expr em uma string no formato JSON.
Sintaxe
STRING TO_JSON(<expr>)
Parâmetros
expr: Obrigatório. Expressão de tipo de dados complexo. O tipo deve ser ARRAY, MAP ou STRUCT.
Se a entrada for do tipo STRUCT (struct<key1:value1, key2:value2):
Ao converter o tipo STRUCT para uma string JSON, todas as chaves assumem letras minúsculas.
Caso um
valueseja NULL, o grupo de dados que contém essevalueé excluído da saída. Por exemplo, sevalue2for NULL, o parkey2:value2não aparecerá na string JSON de saída.Execute o comando
SET odps.sql.bigquery.compatible=true;para ativar o modo compatível com BigQuery. Nesse modo, se um valor for NULL, o par chave-valor correspondente será incluído na saída. Por exemplo, se value2 for NULL, key2:NULL constará na saída.
Valor de retorno
Retorna uma string no formato JSON.
Exemplos
-
Exemplo 1: Converter um tipo complexo em uma string JSON. Comando de exemplo:
-- Returns {"a":1,"b":2}. SELECT TO_JSON(NAMED_STRUCT('a', 1, 'b', 2)); -- Returns {"time":"26/08/2015"}. SELECT TO_JSON(NAMED_STRUCT('time', "26/08/2015")); -- Returns [{"a":1,"b":2}]. SELECT TO_JSON(ARRAY(NAMED_STRUCT('a', 1, 'b', 2))); -- Returns {"a":{"b":1}}. SELECT TO_JSON(MAP('a', NAMED_STRUCT('b', 1))); -- Returns {"a":1}. SELECT TO_JSON(MAP('a', 1)); -- Returns [{"a":1}]. SELECT TO_JSON(ARRAY((MAP('a', 1)))); -
Exemplo 2: Tratar um valor NULL em uma expressão do tipo STRUCT. Comando de exemplo:
-- Returns {"a":"B"}. When the STRUCT type is converted to a JSON string, all keys are converted to lowercase. SELECT TO_JSON(NAMED_STRUCT("A", "B")); -- Returns {"k2":"v2"}. The group of data that contains a NULL value is not included in the output JSON string. SELECT TO_JSON(NAMED_STRUCT("k1", CAST(NULL AS STRING), "k2", "v2")); -
Exemplo 3: Converter uma expressão do tipo STRUCT com um valor NULL no modo compatível com BigQuery. Comando de exemplo:
-- Returns {"k1":null,"k2":"v2"} SET odps.sql.bigquery.compatible=true; SELECT TO_JSON(named_struct("k1", CAST(NULL AS STRING), "k2", "v2")); -- Returns {"id":null,"tag":null,"group":null,"success":true} SET odps.sql.bigquery.compatible=true; SELECT TO_JSON(struct(experiment_id AS id,tag AS tag,`group`,`success`)) AS experiment_in_json FROM( SELECT CAST(NULL AS string) AS experiment_id, CAST(NULL AS string) AS tag, CAST(NULL AS string) AS `group`, TRUE AS `success` );