SQLite json_object() Function

The SQLite json_object() function returns a JSON object containing all the key-value pairs specified by the parameters.

Syntax

Here is the syntax of the SQLite json_object() function:

json_object(key, value[, key2, value2, ...])

Parameters

key

Required. The key in the object.

value

Required. The value of key in the object.

Return value

The json_object() function evaluates all key-value pairs in the arguments list and returns a JSON object containing all the key-value pairs.

Since all keys in the JSON object are strings, json_object() converts non-string values of key to string values. In order to ensure the stability of the program, please provide the key in string type.

If there are duplicates in the parameters key, json_object() will keep all key in the JSON object. This is a mistake.

Examples

Here are some examples of json_object().

Example 1

SELECT json_object('name', 'Jim', 'age', 20);
json_object('name', 'Jim', 'age', 20)
-------------------------------------
{"name":"Jim","age":20}

Here, the returned JSON object of json_object() consists of two members: name and age, and the value of name is 'Jim', the value of age is 20.

Duplicate Keys in json_object()

If there are duplicate key in the parameters list of json_object(), json_object() will keep all key-value pairs. This is a mistake.

SELECT json_object('name', 'Jim', 'age', 20, 'name', 'Tim');
json_object('name', 'Jim', 'age', 20, 'name', 'Tim')
----------------------------------------------------
{"name":"Jim","age":20,"name":"Tim"}

Absolutely, this is a error JSON. A valid JSON Object should not have two identical keys.

Contains complex objects

Complex JSON objects can store more information.

SELECT json_object(
        'name',
        'Tim',
        'age',
        20,
        'friend',
        json_object('name', 'Jim', 'age', 20),
        'hobby',
        json_array('games', 'sports')
    );
json_object(
------------------------------------------------------------
{"name":"Tim","age":20,"friend":{"name":"Jim","age":20},"hob
by":["games","sports"]}

Here, we created the following JSON object:

{
  "age": 20,
  "name": "Tim",
  "hobby": ["games", "sports"],
  "friend": { "age": 20, "name": "Jim" }
}

In this Example:

  • The value of hobby is an array, computed by the json_array() function.
  • The value of friend is an object, computed by the json_object() function.