I need to extract values from a column which has a JSON format. Here is an example of one of rows in table for this column, here is two operatorKeys but in other rows there might be more:
{
"officeId": "office8685",
"TypeOfOffice": null,
"Telefonnummer": "",
"Operatorer": [
{
"OperatorKey": "1",
"OperatorUserID": {
"Agency": "Other",
"AgencySpecified": true,
"Value": "TM-Oper-1"
},
"ContactInformation": {
"FirstName": "mike",
"LastName": null,
"Address": {
"Street": null,
"City": null,
"Province": null,
"Country": null
},
"Phone": null,
"Fax": null,
"Email": null,
}
},
{
"OperatorKey": "4",
"OperatorUserID": {
"Agency": "Other",
"AgencySpecified": true,
"Value": "TM-Oper-4"
},
"ContactInformation": {
"FirstName": "xxx",
"LastName": null,
"Address": {
"Street": null,
"City": null,
"Province": null,
"Country": null
},
"Phone": null,
"Fax": null,
"Email": null,
}
}
]
}
And here is SQL view I'm trying to read JSON, I'm using openjson
and cross apply
to read values:
Alter view dbo.vOffice as
select
column1,column2
--,column3 --this column contains values with json format
,OfficId,TypeOfOffice,Telefonnummer,Operatorer,OperatorKey,OperatorUserID
,ContactInformation,Agency,AgencySpecified,[Value],FirstName,LastName
,[Address],Phone, Fax, Email
FROM [produktion_dim].[VirkesverdeStandardSCD1]
CROSS APPLY OPENJSON (column3,'$.OfficId') with (
OfficId varchar(4096) '$.OfficId',TypeOfOffice varchar(4096) '$.TypeOfOffice',
Telefonnummer varchar(4096) '$.Telefonnummer',Operatorer varchar(4096) '$.Operatorer')
cross apply openjson(Operatorer, '$') with(OperatorKey varchar(4096) '$.OperatorKey', OperatorUserID varchar(4096) '$.OperatorUserID', ContactInformation varchar(4096) '$.ContactInformation')
cross apply openjson(OperatorUserID,'$') with ( Agency varchar(4096) '$.Agency',
AgencySpecified varchar(4096) '$.AgencySpecified',[Value] varchar(4096) '$.Value' )
cross apply openjson( ContactInformation, '$') with (FirstName varchar(4096) '$.FirstName',LastName varchar(4096) '$.LastName',[Address] varchar(4096) '$.Address',Phone varchar(4096) '$.Phone',Fax varchar(4096) '$.Fax',Email varchar(4096) '$.Email')
cross apply openjson([Address],'$') with ( Street varchar(4096) '$.Street',
City varchar(4096) '$.City',Province varchar(4096) '$.Province',Country varchar(4096) '$.Country')
But I'm getting error. Can you please tell me what is missing or what should be changed in SQL view?