All Products
Search
Document Center

MaxCompute:TO_JSON

Last Updated:Nov 03, 2023

Converts an expression of a given complex data type into a JSON string.

Syntax

string to_json(<expr>)

Parameters

expr: required.

Note

If the input expression is of the STRUCT type (struct<key1:value1, key2:value2>), take note of the following points:

  • All keys are converted into lowercase letters when you convert the expression into a JSON string.

  • If a value is null, the key-value pair to which the value belongs is not included in the JSON string that is returned. For example, if value2 is null, key2:value2 is not included in the JSON string that is returned.

Return value

A JSON string is returned.

Examples

  • Example 1: Convert an expression of a given complex data type into a JSON string. Sample statements:

    -- The return value is {"a":1,"b":2}. 
    select to_json(named_struct('a', 1, 'b', 2));
    -- The return value is {"time":"26/08/2015"}. 
    select to_json(named_struct('time', "26/08/2015"));
    -- The return value is [{"a":1,"b":2}]. 
    select to_json(array(named_struct('a', 1, 'b', 2)));
    -- The return value is {"a":{"b":1}}. 
    select to_json(map('a', named_struct('b', 1)));
    -- The return value is {"a":1}. 
    select to_json(map('a', 1));
    -- The return value is [{"a":1}]. 
    select to_json(array((map('a', 1))));
  • Example 2: The input expression is of the STRUCT type. Sample statements:

    -- The return value is {"a":"B"}. If the expression of the STRUCT type is converted into a JSON string, all keys are converted into lowercase letters. 
    select to_json(named_struct("A", "B"));
    -- The return value is {"k2":"v2"}. The key-value pair to which null belongs is not included in the JSON string that is returned. 
    select to_json(named_struct("k1", cast(null as string), "k2", "v2"));

Related functions

TO_JSON is a complex type function or a string function.

  • For more information about the functions that are used to process data of complex data types, such as ARRAY, MAP, STRUCT, and JSON, see Complex type functions.

  • For more information about functions related to string searches and conversion, see String functions.