GVR
GVR

Reputation: 330

Is it possible to use cockroach gen_random_uuid() function inside JSON data while inserting into JSON datatype in cockroachDB

I am new to cockroach DB and was wondering if the below ask is possible

One of the columns in my table is of JSON type and the sample data in it is as follows

 {
    "first_name": "Lola",
    "friends": 547,
    "last_name": "Dog",
    "location": "NYC",
    "online": true,
    "Education": [
        {
            "id": "4ebb11a5-8e9a-49dc-905d-fade67027990",
            "UG": "UT Austin",
            "Major": "Electrical",
            "Minor": "Electronics"
        },
        {
            "id": "6724adfa-610a-4efe-b53d-fd67bd3bd9ba",
            "PG": "North Eastern",
            "Major": "Computers",
            "Minor": "Electrical"
        }
    ]
}

Is there a way to replace the "id" field in JSON as below to get the id generated dynamically?

"id": gen_random_uuid(),

Upvotes: 0

Views: 490

Answers (1)

paulkernfeld
paulkernfeld

Reputation: 2216

Yes, this should be possible. To generate JSON data that includes a randomly-generated UUID, you can use a query like:

root@:26257/defaultdb> select jsonb_build_object('id', gen_random_uuid());
                jsonb_build_object
--------------------------------------------------
  {"id": "d50ad318-62ba-45c0-99a4-cb7aa32ad1c3"}

If you want to update in place JSON data that already exists, you can use the jsonb_set function (see JSONB Functions).

Upvotes: 1

Related Questions