简体   繁体   中英

Query elements in a nested array of a json object in postgresql 9.4 or 9.5

{
  "studentID": 1,
  "StudentName": "jhon",
   "Data":{
     "schoolname":"school1",
     "enrolmentInfo":
           [{  
              "year":"2015",
              "info": 
                    [
                     {
                      "courseID":"csc213",
                      "school":"IT",
                      "enrollmentdate":"2015-01-01",
                      "finshdate":"2015-07-01",
                      "grade": 80 },

                      {
                      "courseID":"csc113",
                      "school":"IT1",
                      "enrollmentdate":"2015-09-02",
                      "finshdate":null,
                      "grade": 90 } ]
               },
             {  
              "year":"2014",
              "info": 
                    [{
                      "courseID":"info233",
                      "school":"IT",
                      "enrollmentdate":"2014-03-11",
                      "finshdate":"2014-09-01",
                      "grade": 81 },

                      {
                      "courseID":"csc783",
                      "school":"IT",
                      "enrollmentdate":"2014-01-02",
                      "finshdate":"2014-08-01",
                      "grade": 87 } ]
              }  ]
        }

     }

I have stored in postgresql database json objects of the above format. Each object consists of informations about a certain student with enrollment information. I have complex objects with nested array inside arrays. I am trying to select all the element inside the "info" array. I tried to use the following query:

 with recursive x (info) as (select value->'info' from jsontesting r,  json_array_elements(r.data->'Data'->'enrolmentinfo') 
 UNION ALL 
 SELECT  (e).value->'courseID', (e).value->'school', (e).value->'grade',(e).value->'enrollmentdate', (e).value->'finshdate'   
 from (select json_each(json_array_elements (info)) e from x) p)
 select * from x;

This query is not working and it is giving the following error:"cannot call json_array_elements on a scalar". Is there any other query that I can use to extract the elements of the nested array "info"??

-- assuming that jsontesting.data contains your JSON    
WITH info_data AS (
   SELECT enrolment_info->'info' AS info
   FROM jsontesting t, json_array_elements(t.data -> 'Data' -> 'enrolmentInfo') AS enrolment_info
)
SELECT info_item->>'courseID',
       info_item->>'school',
       info_item->>'enrollmentdate',
       info_item->>'finshdate',
       info_item->>'grade'
FROM info_data idata, json_array_elements(idata.info) AS info_item;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM