简体   繁体   中英

Parse JSON Array of arrays to SQL table

I have a JSON response from API like below:

{
  "series":[
   {
    "series_id": "SER_ID_1",
    "data": [
          ["20200101",
           1.0
          ],
          ["20200102",
           1.9
          ],
          ["20200103",
           4.5
          ]
        ]
  },
  {
    "series_id": "SER_ID_2",
    "data": [
          ["20200101",
           6.0
          ],
          ["20200102",
           8.9
          ],
          ["20200103",
           1.5
          ]
        ]
  }
 ]
}

There can be N series and there can be N values in data .

I want to parse this JSON in SQL so that I get the below results:

series_id       date        value
SER_ID_1        20200101.   1.0
SER_ID_1        20200102.   1.9
SER_ID_1        20200103.   4.5
SER_ID_2        20200101.   6.0
SER_ID_2        20200102.   8.9
SER_ID_2        20200103.   1.5

Please provide a SQL server query to get the desired result on parsing JSON.

Thanks in advance.

You need to parse the input JSON using OPENJSON() twice with the appropriate explicit schemas. Of course, you need SQL Server 2016+ to use the built-in JSON support.

JSON:

DECLARE @json nvarchar(max) = N'
{
  "series":[
    {
    "series_id": "SER_ID_1",
    "data": [["20200101", 1.0], ["20200102", 1.9], ["20200103", 4.5]]
    },
    {
    "series_id": "SER_ID_2",
    "data": [["20200101", 6.0], ["20200102", 8.9], ["20200103", 1.5]]
    }
  ]
}'

Statement:

SELECT j1.series_id, j2.[date], j2.[value]
FROM OPENJSON(@json, '$.series') WITH (
   series_id varchar(10) '$.series_id',
   data nvarchar(max) '$.data' AS JSON
) j1
OUTER APPLY OPENJSON(j1.data) WITH (
   [date] date '$[0]',
   [value] numeric(5, 1) '$[1]'
) j2

Result:

series_id   date       value
SER_ID_1    2020-01-01   1.0
SER_ID_1    2020-01-02   1.9
SER_ID_1    2020-01-03   4.5
SER_ID_2    2020-01-01   6.0
SER_ID_2    2020-01-02   8.9
SER_ID_2    2020-01-03   1.5

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