James Sumners
James Sumners

Reputation: 14777

How do I create a new JSON object with PL/JSON?

Let's say I want to create the following JSON structure in PL/JSON:

{
  "foo": "bar",
  "baz": 42,
  "foobar": [ 1, 2, 3 ]
}

How do I do it?

Upvotes: 1

Views: 8010

Answers (1)

James Sumners
James Sumners

Reputation: 14777

The simplest method is to simply pass the string to the JSON type constructor like so:

declare
  json_obj json;
begin
  json_obj := json('{"foo":"bar", "baz":42, "foobar": [1,2,3]}');
end;
/

But let's pretend you are building this JSON object from data in your database. Then you would do something like the following:

declare
  json_obj json := json();
  json_ar  json_list := json_list();
begin
  -- Add the string elements
  json_obj.put('foo', 'bar');
  json_obj.put('baz', 42);

  -- Add elements to the array ("list" in PL/JSON)
  json_ar.append(1);
  json_ar.append(2);
  json_ar.append(3);
  -- Add the array to the object
  json_obj.put('foobar', json_ar);

  -- Print it just for fun
  json_obj.pretty_print
end;
/

Upvotes: 5

Related Questions