Parse JSON in SQL - sql

I'm looking to parse a single return in JSON into multiple rows.
The string is this -
{"policy_ids":["INZP2981-11000002","INZP-00001786","0AAAA01PC06"]}
I want to just parse this so that it is a row for each policy_ids. I've tried using OpenJSON WITH however I keep returning NULL values.
DECLARE #json NVARCHAR(MAX) ;
SET #json = N'{"policy_ids":["INZP2981-11000002","INZP-00001786","0AAAA01PC06"]}' ;
SELECT
*
FROM
OPENJSON(#json)
WITH (
policy_ids varchar(200) '$.policy_ids'
)
Help is appreciated.

You need a different statement to parse the $.policy_ids JSON array. You may try tou use OPENJSON() with default schema (without the WITH clause). In this case the result is a table with columns key, value and type and the value column returns the value of each item in the input array.
DECLARE #json NVARCHAR(MAX) ;
SET #json = N'{"policy_ids":["INZP2981-11000002","INZP-00001786","0AAAA01PC06"]}' ;
SELECT [value] AS policy_id
FROM OPENJSON(#json, '$.policy_ids')
Result:
policy_id
-----------------
INZP2981-11000002
INZP-00001786
0AAAA01PC06
If you want to use an explicit schema, the statement is:
SELECT *
FROM OPENJSON(#json, '$.policy_ids') WITH (
policy_id varchar(200) '$'
)

Related

Select specific value from JSON list with SQL

Suppose I have a table column with person data organized as a JSON array, with categories and names.
In SQL, I can then easily select the data for a specific element in the array:
SELECT JSON_VALUE('{ "Persons": [{"PersonCat":"1","Name":"John"},{"PersonCat":"2","Name":"Henry"}]}','$.Persons[0].Name') AS SelectedPerson
I will then get "John".
But what if I want the person with "PersonCat" = 2? And null if PersonCat does not exist in the list?
I'm not sure it is possible to do this with the JSON_VALUE method, but it is possible using OPENJSON
DECLARE #json nvarchar(max)
SET #json = '{ "Persons": [{"PersonCat":"1","Name":"John"},{"PersonCat":"2","Name":"Henry"},{"Name":"Bob"}]}'
SELECT[PersonCat], [Name]
FROM OPENJSON(#json, '$.Persons')
WITH (
PersonCat NVARCHAR(512) '$.PersonCat',
[Name] NVARCHAR(512) '$.Name'
)
You can then add a WHERE clause to the SELECT to find the relevant PersonCat value (note: where the PersonCat property is missing from the array entry, the PersonCat column will be NULL)

how can I store Json query in SQL?

I have to write Json and I dont know how could i store that query in SQL Server
my code is this:
DECLARE #JsonData AS NVARCHAR(MAX) = (SELECT FID, Ftype, Fcount, Datetype, Fregion
FROM FoodSara_tbl
FOR JSON AUTO)
and if I write SELECT ISJSON(#JsonData ) it returns 1
how can I store Json query in SQL?
PS: I dont't want write it in SP
DECLARE #JsonData AS NVARCHAR(MAX) =
CAST((SELECT FID, Ftype, Fcount, Datetype, Fregion
FROM FoodSara_tbl
FOR JSON AUTO) AS NVARCHAR(max));
Because a query returns a dataset !... You need to specify that the single value returned in the dataset must be casted in string...

SQL - openjson to extract key from json

Below #json contains 3 data object within an array. After using OPENJSON to extract these objects to a Table variable, please see the output attached.
DECLARE #json NVARCHAR(MAX);
SET #json = N'[{"Container":"MSKU2913236","Seal":"ML-TH4773979","Size":"20","Temperature":"-20","TareWeight":"3.132","CreatedDate":"02-02-2018 00:00:00","Comment":null,"NetWeight":"21.445","TempRec#":null},{"Container":"MSKU3432702","Seal":"ML-TH4773972","Size":"20","Temperature":"-40","TareWeight":"2.872","CreatedDate":"02-02-2018 00:00:00","Comment":null,"NetWeight":"23.932","TempRec#":"TR12345"},{"Container":"MSKU4043053","Seal":"ML-TH4773973","Size":"20","Temperature":"-20","TareWeight":"2.995","CreatedDate":"02-02-2018 00:00:00","Comment":null,"NetWeight":"22.4","TempRec#":null}]';
DECLARE #ContainerTable TABLE(
[Key] NVARCHAR(100),
[Data] NVARCHAR(MAX)
);
INSERT INTO #ContainerTable
SELECT [key], [value] FROM OPENJSON(#json)
SELECT * FROM #ContainerTable
Output
Objective is to replace the Key column values with the Container property value from json in the Data column for all 3 rows.
Expected Output
Note: Expected output is hard coded and it only shows the one row but same is required for all rows.
You could use JSON_VALUE:
INSERT INTO #ContainerTable([Key], [Data])
SELECT JSON_VALUE([value],'$.Container'), [value]
FROM OPENJSON(#json);
DBFiddle Demo

SQL 2017 : Need to convert json with column name as a value and actual value is value of another one

HI I need to convert Json stored in 1 of the columns in a table to flat tables with specific fields.
Note : Column names are not always ""Request type,Country...".Columsn are dynamic and should be picked from value in "Name"
Below is the json from 1 row.
{"JobID":1,"ItemID":1,"Attributes":[{"ID":1,"Name":"Request Type","Value":"1","ValueString":"Buy"},{"ID":3,"Name":"Country","Value":"2","ValueString":"USA"},{"ID":5,"Name":"Number","Value":"1","ValueString":"1"}]}
I need this to be converted as in attached format
As a starter you should check OPENJSON:
DECLARE #j NVARCHAR(MAX) = '{"JobID":1,"ItemID":1,"Attributes":[{"ID":1,"Name":"Request Type","Value":"1","ValueString":"Buy"},{"ID":3,"Name":"Country","Value":"2","ValueString":"USA"},{"ID":5,"Name":"Number","Value":"1","ValueString":"1"}]}'
And query:
SELECT *
FROM OPENJSON(#j)
WITH (JobID INT '$.JobID',
ItemId INT '$.ItemID',
[Request_Type] NVARCHAR(100) '$.Attributes[0].ValueString',
Country NVARCHAR(100) '$.Attributes[1].ValueString',
[Number] NVARCHAR(100) '$.Attributes[2].ValueString'
);
DBFiddle Demo

Create temp table from comma separated values with more than one column

I'm trying to pass a comma separated string such as this: "101:string1,102:string2" into a stored proc and create a temp table out of it. The temp table would have two columns, one integer and one string. It would have two rows for this example. The comma delimits the rows, and the colons delimit the two columns. Anyone know how I can do this? I'm using sql server. Thanks in advance!
EDIT: By the way, I'm not asking about how to create a temp table, only how to create the function.
You can try a Table-Valued Function instead of a temp table. Something like this:
CREATE FUNCTION ListToTable
(
#list nvarchar(4000)
)
RETURNS #return TABLE
(
n int,
s nvarchar(15)
)
AS
BEGIN
SET #list = NULLIF(ltrim(rtrim(#list)),'')
DECLARE #xml AS XML = CAST('<root><row><n>' +
REPLACE(REPLACE(#list,
',', '</s></row><row><n>'),
':', '</n><s>') +
'</s></row></root>' AS XML) ;
INSERT INTO #return (n, s)
SELECT root.row.value('n[1]', 'int')
, root.row.value('s[1]', 'nvarchar(4000)')
FROM #xml.nodes('/root/row') as root(row)
RETURN
END
Usage:
select * from dbo.ListToTable('101:string1,102:string2')
Output:
n s
----------- ---------------
101 string1
102 string2