Skip to Main Content
  • Questions
  • Combine json objects into one document

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Don.

Asked: April 29, 2019 - 3:49 pm UTC

Last updated: April 30, 2019 - 4:47 pm UTC

Version: 12c

Viewed 1000+ times

You Asked

I need to combine some existing json objects into a new json object. Using the syntax:

json3 := json_object('json1' value json1, 'json2' value json2);


the existing json objects get wrapped in an extra set of double quotes, and the embedded double quotes get escaped. Without rebuilding the json objects (as in the fifth output), how can I accomplish this?

Thanx, D


with LiveSQL Test Case:

and Chris said...

Use the format json clause. Or if you're on 18c you can use treat ( ... as json ):

declare  
    json1 varchar2(200); 
    json2 varchar2(200); 
    json3 varchar2(200);  
     
begin  
    json1 := json_object('1' value 1, '2' value 2, '3' value 3);  
    DBMS_OUTPUT.put_line (json1);  
     
    json2 := json_object('state' value 'AZ', 'car' value 'P1', 'pet' value 'Dog');  
    DBMS_OUTPUT.put_line (json2);  
     
    select json_object( 
      'json1' value json1 format json,  
      'json2' value json2 format json
    ) 
    into json3 
    from dual;  
    DBMS_OUTPUT.put_line (json3);  
     
    select json_object ( 
      'json1' value treat ( json1 as json ),  
      'json2' value treat ( json2 as json )
    ) 
    into json3 
    from dual;  
    DBMS_OUTPUT.put_line (json3);  
     
end; 
/

{"1":1,"2":2,"3":3}
{"state":"AZ","car":"P1","pet":"Dog"}
{"json1":{"1":1,"2":2,"3":3},"json2":{"state":"AZ","car":"P1","pet":"Dog"}}
{"json1":{"1":1,"2":2,"3":3},"json2":{"state":"AZ","car":"P1","pet":"Dog"}}

Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Don Simpson, April 30, 2019 - 3:46 pm UTC

Thank you so much. I tried the "format json" with the
json3 := json_object(...)
syntax, but that's not valid and it didn't occur to me to try it with the
select json_object(...) into json3
syntax.

Chris Saxon
April 30, 2019 - 4:47 pm UTC

Happy to help.

More to Explore

SQL

The Oracle documentation contains a complete SQL reference.