Is there an UPDATE equivalent command to SELECT json data - sql

Is there a way to update the data retrieved from the below select (in this case, change "MS220" to something else)? It's difficult enough to do select from JSON in some cases. I'm not sure how to update just a single element.
CREATE TABLE JData (
JsonData nvarchar(max)
)
INSERT INTO JData
(JsonData)
VALUES
('[
{
"Categories": [
{
"QuerySourceNames": [
"QAsset"
],
"Id": "eceae85a-ffc6-49f4-8f6a-78ce2b4b274e",
"Name": "emsdba"
}
],
"Id": "525b4f07-0f67-43ac-8070-a0e6c1ceb1b9",
"Name": "MS220"
}
]')
SELECT
ParamName
FROM [dbo].[JData] jsonData
CROSS APPLY OPENJSON (jsonData)
WITH
(
Categories nvarchar(max) AS json,
Id uniqueidentifier,
ParamName varchar(10) '$.Name'
);

Try JSON_MODIFY() with the path '$[0].Name'
UPDATE d
SET jsonData = JSON_MODIFY(jsonData, '$[0].Name', 'New Value')
FROM [dbo].[JData] d
Results:
[
{
"Categories": [
{
"QuerySourceNames": [
"QAsset"
],
"Id": "eceae85a-ffc6-49f4-8f6a-78ce2b4b274e",
"Name": "emsdba"
}
],
"Id": "525b4f07-0f67-43ac-8070-a0e6c1ceb1b9",
"Name": "New Value"
}
]
db<>fiddle here

Related

Extract text from JSON in SQL Server

I am trying to extract a specific value from a JSON column in SQL Server. Unfortunately I have read several posts on this topic but still cannot figure out how to translate their solutions to what I need. I am looking to extract "foo testing" but simply do not understand how to get at this with a nested JSON. Can someone please advise?
The structure of the JSON column is:
{
"values": [
{
"id": "x01",
"status": "STATUS1",
"subStatus": "SubStatus1",
"values": [
{
"key": "dropdown",
"value": "",
"optionType": null
}
]
},
...
{
"id": "x03",
"status": "STATUS3",
"subStatus": "SubStatus3",
"values": [
{
"key": "dropdown",
"value": "",
"optionType": null
},
{
"key": "textInput",
"value": null,
"optionType": null
},
{
"key": "checkbox1",
"value": true,
"optionType": null
},
{
"key": "textInput2",
"value": "foo testing",
"optionType": null
}
]
}
]
}
The statement depends on the structure of the parsed JSON, in your case you need to use two nested OPENJSON() calls and additinal APPLY operators. Note, that you need to use AS JSON in a "values" column definition to specify that the referenced property contains an inner JSON array and the type of that column must be nvarchar(max).
Test table:
DECLARE #json varchar(max) = '
{
"values": [
{
"id": "x01",
"status": "STATUS1",
"subStatus": "SubStatus1",
"values": [
{"key": "dropdown", "value": "", "optionType": null}
]
},
{
"id": "x03",
"status": "STATUS3",
"subStatus": "SubStatus3",
"values": [
{"key": "dropdown", "value": "", "optionType": null},
{"key": "textInput", "value": null, "optionType": null},
{"key": "checkbox1", "value": true, "optionType": null},
{"key": "textInput2", "value": "foo testing", "optionType": null}
]
}
]
}
'
SELECT JsonColumn
INTO JsonTable
FROM (VALUES (#json)) v (JsonColumn)
Statement:
SELECT j1.[id], j2.[key], j2.[value] -- or add all columns
FROM JsonTable t
CROSS APPLY OPENJSON(t.JsonColumn, '$.values') WITH (
[id] varchar(3) '$.id',
[status] varchar(30) '$.status',
[subStatus] varchar(30) '$.subStatus',
[values] nvarchar(max) '$.values' AS JSON
) j1
CROSS APPLY OPENJSON(j1.[values], '$') WITH (
[key] varchar(50) '$.key',
[value] varchar(50) '$.value',
[optionType] varchar(50) '$.optionType'
) j2
Result:
id key value
---------------------------
x01 dropdown
x03 dropdown
x03 textInput
x03 checkbox1 true
x03 textInput2 foo testing
you can use following query
;with summery as(
SELECT *
FROM OPENJSON((SELECT value FROM OPENJSON(#json)))
WITH (
id NVARCHAR(50) 'strict $.id',
status NVARCHAR(50) '$.status',
subStatus NVARCHAR(50) '$.subStatus',
[values] NVARCHAR(max) '$.values' AS JSON
)
)
select id,status,subStatus,[key],value,optionType from summery
CROSS APPLY OPENJSON(summery.[values])
WITH (
[key] NVARCHAR(50) '$.key',
[value] NVARCHAR(50) '$.value',
[optionType] NVARCHAR(50) '$.optionType'
);
demo in db<>fiddle

How to retrieve specific JSON value from a column containing a JSON array

I have this JSON array in a SQL Server table:
[
{
"FieldName": "DateCreated",
"FieldValue": "10/22/2020"
},
{
"FieldName": "IsMember",
"FieldValue": "false"
},
{
"FieldName": "EntityId",
"FieldValue": "ABC123"
}
]
I want to fetch only the FieldValue of the EntityId object, so the output should be only ABC123.
I have this query
SELECT JSON_VALUE(JsonColumnData, '$[2].FieldValue') AS EntityId
FROM MyTable
This returns the EntityId value, but the thing is that I have no guarantee that the EntityId will always be in the same position of the JSON array.
Is it possible to have the select return the EntityId regardless of its position in the JSON array?
You can use OPENJSON() to query the data and just filter the row(s) that contain EntityId...
create table dbo.MyTable (
JsonColumnData nvarchar(max)
);
insert dbo.MyTable (JsonColumnData) values (N'[
{
"FieldName": "DateCreated",
"FieldValue": "10/22/2020"
},
{
"FieldName": "IsMember",
"FieldValue": "false"
},
{
"FieldName": "EntityId",
"FieldValue": "ABC123"
}
]');
select FieldValue as EntityId
from dbo.MyTable
cross apply openjson(JsonColumnData) with (
FieldName nvarchar(11),
FieldValue nvarchar(11)
)
where FieldName = N'EntityId';
Which yields...
EntityId
---------
ABC123

Advice on using OPENJSON to parse a nested array

I am hoping somebody can help point me in the right direction as Iā€™m trying to parse a json file into sql using OPENJSON. I have a structure which looks like this:
DECLARE #json AS NVARCHAR(MAX) = '
[{
"id": "78",
"Version": {
"Value": "12"
},
"Names": [{
"NameId": {
"Value": "8516365"
},
"id": "328787",
"NameLinkType": {
"Value": "A"
"CommsChains": {
"Value": [[{
"com_primary": {
"Value": "Y"
},
"com_recd": {
"Value": "2020-07-07 00:00:00.000"
},
"com_ack": {
"Value": "2020-07-09 00:00:00.000"
},
}
]]
), },
},
],
}
]'
I am able to parse the majority of the JSON correctly, so for each ID I can return values such as Version or NameId. However, I am unable to return any dates in respect of com_recd or com_ack, which sit under CommsChains [Object] ā€“ Value [Array] ā€“ [0] [Array]
It looks like there are some syntactic errors in your JSON. After having them fixed, I was able to try and find the JSON paths to the date expressions to the date values. This is the SQL:
DECLARE #json AS NVARCHAR(MAX) = '
[{
"id": "78",
"Version": {
"Value": "12"
},
"Names": [{
"NameId": {
"Value": "8516365"
},
"id": "328787",
"NameLinkType": {
"Value": "A",
"CommsChains": {
"Value": [[{
"com_primary": {
"Value": "Y"
},
"com_recd": {
"Value": "2020-07-07 00:00:00.000"
},
"com_ack": {
"Value": "2020-07-09 00:00:00.000"
}
}
]]
}
}
}
]
}
]'
select * from openjson(#json, '$[0].Version');--Value 12 1
select * from openjson(#json, '$[0].Names');
select * from openjson(#json, '$[0].Names[0]');
select * from openjson(#json, '$[0].Names[0].NameLinkType');
select * from openjson(#json, '$[0].Names[0].NameLinkType.CommsChains');
select * from openjson(#json, '$[0].Names[0].NameLinkType.CommsChains.Value');
select * from openjson(#json, '$[0].Names[0].NameLinkType.CommsChains.Value[0]');
select * from openjson(#json, '$[0].Names[0].NameLinkType.CommsChains.Value[0][0]');
select * from openjson(#json, '$[0].Names[0].NameLinkType.CommsChains.Value[0][0].com_recd'); --selecting path for com_recd
select * from openjson(#json, '$[0].Names[0].NameLinkType.CommsChains.Value[0][0].com_ack'); --selecting path for com_ack
Herein I show the selects to the different parts of your JSON. The arrays'content are always referenced as [0] as its always the first index to select here.
For more information on JSON paths on the SQL server look here

SQL Query to get the count of Json Array

I have the below Json object. How do I get the count of Object Array.
{
"Model": [
{
"ModelName": "Test Model",
"Object": [
{
"ID": 1,
"Name": "ABC"
},
{
"ID": 11,
"Name": "ABCD"
},
]
}]}
I tried the below query but seems JSON_Length was not available.
SELECT ModelName,
JSON_LENGTH(JsonData, '$.Model[0].Object')
FROM TabA
The expected output should be
ModelName COUNT
Test Model 2
If you have valid JSON (at the moment you have a trailing comma (,_ after one of your closing braces (})), then you could use OPENJSON and COUNT:
DECLARE #JSON nvarchar(MAX) = N'{
"Model": [
{
"ModelName": "Test Model",
"Object": [
{
"ID": 1,
"Name": "ABC"
},
{
"ID": 11,
"Name": "ABCD"
}
]
}]}';
SELECT M.ModelName,
COUNT(O.[key]) AS [Count]
FROM (VALUES(#JSON))V(J)
CROSS APPLY OPENJSON(V.J)
WITH(ModelName varchar(20) '$.Model[0].ModelName',
[Object] nvarchar(MAX) '$.Model[0].Object' AS JSON) M
CROSS APPLY OPENJSON(M.[Object]) O
GROUP BY M.ModelName;

Reading json array into rows in SQL Server

Given the sample json data below, how can I write a query to pull the array data all in one step? My goal is to have one row for each item in the ActionRecs array (4). My actual json is more complicated but I think this gives a good example of my goal.
declare #json2 nvarchar(max)
set #json2 = '{
"RequestId": "1",
"ActionRecs": [
{
"Type": "Submit",
"Employee": "Joe"
},
{
"Type": "Review",
"Employee": "Betty"
},
{
"Type": "Approve",
"Employee": "Sam"
},
{
"Type": "Approve",
"Employee": "Bill"
}
]
}'
SELECT x.*
, JSON_QUERY(#json2, '$.ActionRecs') as ActionArray
from OPENJSON(#json2)
with (Id varchar(5) '$.RequestId') as x
One possible approach is to use OPENJSON() with explicit schema and an additional CROSS APPLY operator:
DECLARE #json nvarchar(max)
SET #json = N'{
"RequestId": "1",
"ActionRecs": [
{"Type": "Submit", "Employee": "Joe"},
{"Type": "Review", "Employee": "Betty"},
{"Type": "Approve", "Employee": "Sam"},
{"Type": "Approve", "Employee": "Bill"}
]
}'
SELECT i.Id, a.[Type], a.[Employee]
FROM OPENJSON(#json) WITH (
Id varchar(5) '$.RequestId',
ActionRecs nvarchar(max) '$.ActionRecs' AS JSON
) AS i
CROSS APPLY OPENJSON(i.ActionRecs) WITH (
[Type] nvarchar(max) '$.Type',
[Employee] nvarchar(max) '$.Employee'
) a
Output:
Id Type Employee
1 Submit Joe
1 Review Betty
1 Approve Sam
1 Approve Bill