I want to read all elements of a json to get the value as text but I am getting value with double quotes. Also help me how better i will read all the elements of nested json which have multiple array elements.
create table jtest (id integer,doc jsonb);
insert into jtest values
(1, '{
"empdet":{
"isMgr":false,
"deptno":"102",
"selectedDept":{
"deptno":"102",
"empName":"MILLER SALESMAN" },
"selectedMgrs":[
{ "id":"1",
"list":[
{ "mgrName":"KING",
"mgrRole":"KING PRESIDENT" },
{ "mgrName":"SCOTT",
"mgrRole":"SCOTT MGR" }
],
"minApp":"1"
}
]
},
"jobIds":[ 770 ],
"appMgrs":[
{ "mgrId":"KING",
"mgrType":"U"
}
],
"deptLoc":"NEW YORK"
}');
insert into jtest values
(2, '{
"empdet":{
"isMgr":false,
"deptno":"101",
"selectedDept":{
"deptno":"101",
"empName":"SMITH SALESMAN" },
"selectedMgrs":[
{ "id":"2",
"list":[
{ "mgrName":"KING",
"mgrRole":"KING PRESIDENT" },
{ "mgrName":"BLAKE",
"mgrRole":"BLAKE MGR" }
],
"minApp":"1"
}
]
},
"jobIds":[ 775 ],
"appMgrs":[
{ "mgrId":"KING",
"mgrType":"U"
}
],
"deptLoc":"NEW YORK"
}');
select id,
doc-> 'empdet'->'selectedDept'->>'empName' empName,
doc-> 'empdet'->>'deptno' deptno,
jsonb_path_query_first(doc, '$.empdet.selectedMgrs.id' ) id,
jsonb_path_query(doc, '$.empdet.selectedMgrs.list[*]' )->>'mgrRole' mgrRole,
jsonb_path_query(doc, '$.empdet.selectedMgrs.list[*]')->>'mgrName' mgrName,
jsonb_path_query_first(doc, '$.empdet.selectedMgrs.minApp' ) minApp,
jsonb_path_query_first(doc, '$.appMgrs.mgrId') mgrId,
jsonb_path_query_first(doc, '$.appMgrs.mgrType' ) mgrType,
doc->>'deptLoc' deptLoc,
jsonb_path_query_first(doc, '$.jobIds[*]' ) jobIds
from jtest;
2
Answers
The double quotes you’re seeing are because the values you retrieved using
jsonb_path_query()
are ofjsonb
type. You can check usingpg_typeof()
: demoTo get the value without those, you could get the outer object using the function, then get the text value from it with
->>
operator, then maybe even cast it using::int
: demoSince jsonb_path_query_first return jsonb, we need first convert the result to text then remove quotes using
REPLACE
:To access an array for exemple
selectedMgrs
you can usejsonb_array_elements
:To access array of arrays try this :
To get JSON element as text you can use the operator
->>
Demo here