Select part from the values in SQL - sql

I have such problem/question. I am trying to extract data from database, but only part. The real example is:
{
"email":"bla#gmail.com",
"addinfo":{
"invoice_id":"1F5FspmpyfQ"
},
"cardholder":"blabla",
"masked_pan":"123456XXXXXX1234"
}
I need to receive only 1F5FspmpyfQ, all between {"invoice_id": " and "},.

You can use Postgres' JSON functions:
select the_column::jsonb -> 'addinfo' ->> 'invoice_id' as invoice_id
from the_table;
-> returns a json object with the specified key and ->> returns the key's value as a text (rather than jsonb)

You can use JSON functions in SQL Server, but JSON support was not introduced until SQL Server 2016:
DECLARE #json NVARCHAR(MAX);
SET #json = '{
"email":"blablabla",
"addinfo":{
"invoice_id":"1F5FspmpyfQ"
},
"cardholder":"bla bla",
"masked_pan":"12345XXXXXX1234"
}';
SELECT JSON_VALUE(#json, '$.addinfo.invoice_id');

Related

Reading JSON string and find the max value as integer

I have a JSON string as follows:
DECLARE #json nvarchar(max)
SET #json = '{"value": [
{
"AEDAT": "20211110"
},
{
"AEDAT": "20211110"
},
{
"AEDAT": "20211110"
},
{
"AEDAT": "20211112"
},
{
"AEDAT": "20211112"
},
{
"AEDAT": "20211112"
}
]}';
Now I want to read this JSON in SQL Server using OPENJSON() and find the MAX value for each AEDAT. For this, I am using the following query:
SELECT MAX(value)
FROM OPENJSON(#json, '$.value')
The above query is returning a row with key value pair as below:
{"AEDAT":"20211112"}
My objective is to get only 20211112 as integer.
How to achieve this?
If you want to get the max value as integer, you need to use OPENJSON() with explicit schema (the WITH clause with columns definitions). This schema depends on the structure of the parsed JSON (in your case it's a JSON array):
SELECT MAX(AEDAT) AS MaxAEDAT
FROM OPENJSON(#json, '$.value') WITH (
AEDAT int '$.AEDAT'
)
If the parsed values are dates, you may try a different statement:
SELECT MAX(TRY_CONVERT(date, AEDAT, 112)) AS MaxAEDAT
FROM OPENJSON(#json, '$.value') WITH (
AEDAT varchar(8) '$.AEDAT'
)
OPENJSON without explicit schema, gives you the value column which, in your example, will contain an object such as {"AEDAT": "20211110"} having type = 5. Use JSON_VALUE on that object:
select max(cast(json_value(j.value, '$.AEDAT') as int))
from openjson(#json, '$.value') as j

Create JSON string using variable

I am trying to get following JSON string:
[{
"Name": "John",
"AccountType": 1
},
{
"Name": "Steven",
"AccountType": 1
}
]
I know that AccountType will be always 1 and I have string variable in following format "John;Steven;Brian;Mike"
I was trying to build this JSON using XML PATH and splitToTable function but with no success. How can I achieve it?
Thanks in advance.
In SQL Server 2016 Microsoft added some useful JSON functions. So this can be achieved very easily:
DECLARE #Variable nvarchar(max) = 'John;Steven;Brian;Mike';
SELECT [value] as Name, 1 as AccountType FROM STRING_SPLIT(#Variable,';')
FOR JSON PATH
More info about this functions here - https://learn.microsoft.com/en-us/sql/relational-databases/json/json-data-sql-server?view=sql-server-ver15
You can use string_split() and for json:
declare #str nvarchar(max) = 'John;Steven;Brian;Mike';
select *
from (
select value as [Name], 1 as [AccountType]
from string_split(#str, ',')
) t
for json auto;

SQL Server 2017 Selecting JSON embedded within a JSON field

In SQL Server 2017, I'd like to "SELECT" a JSON object embedded within another as a string so we can store/process them later.
eg JSON:
[
{"key1":"value1",
"level2_Obj":{"key2":"value12"}
},
{"key1":"value2",
"level2_Obj":{"key22":"value22"}
},
]
From above JSON, I'd like to SELECT whole of the level2Obj JSON object, see below for what I'd like to see the "selection" result.
value1 |{"key2" :"value12"}
value2 |{"key22":"value22"}
I tried below with no luck:
SELECT * FROM
OPENJSON(#json,'$."data1"')
WITH(
[key1] nvarchar(50),
[embedded_json] nvarchar(max) '$."level2Obj"'
) AS DAP
Can some one please help how I select the contents of the 2nd level JSON object as a string?
The idea is to Write 1st level JSON properties into individual cells and rest of JSON levels into a single column of type nvarchar(max) (i.e whole of sub-level JSON object into a single column as a string for further processing in later stages).
Good day,
Firstly, Your JSON text is not properly formatted. There is extra comma after the last object in the array. I will remove this extra comma for the sake of the answer, but if this is the format you have then first step will be to clear the text and make sure that is is well formatted.
Please check if this solve your needs:
declare #json nvarchar(MAX) = '
[
{
"key1":"value1",
"level2_Obj":{"key2":"value12"}
}
,
{
"key1":"value2",
"level2_Obj":{"key22":"value22"}
}
]
'
SELECT JSON_VALUE (t1.[value], '$."key1"'), JSON_QUERY (t1.[value], '$."level2_Obj"')
FROM OPENJSON(#json,'$') t1

OpenJson using a wildcard

I have a SQL query using OPENJSON to import JSON data into a table. My problem is that the data I need is nested. How can I use a wildcard in the JSON path to get what I need?
SELECT #Set =
BulkColumn FROM OPENROWSET
(BULK 'Sets.json', DATA_SOURCE = 'MyAzureJson', SINGLE_BLOB) JSON;
INSERT INTO [Sets]
SELECT [name]
FROM OPENJSON(#Set)
WITH(
[name] nvarchar(50) '$.*.name'
)
my json file is set up like this..
{
"testOne" : {
name: "nameOne"
},
"testTwo : {
name: "nameTwo"
}
}
the error I'm getting with everything I try..
JSON path is not properly formatted. Unexpected character '*' is found at position 2.
I've tried . * [] and nothing works
As far as I know there is no support for wildcards in OPENJSON.
Instead you can do a workaround by ignoring the field name in your search. Use JSON_VALUE for this.
INSERT INTO [Sets]
SELECT
JSON_VALUE([value], '$.name')
FROM
OPENJSON(#Set)
Explanation: If you don't define the variables of OPENJSON inside a WITH clause and instead do a simple SELECT * FROM OPENJSON(#Set) query, you will get a result with key, value and type columns (see example output below). Because key contains your problematic field name, you can ignore that part and just look into the value column of the data.
[key] [value] [type]
----- ------- ------
testOne { name: "nameOne" } 5
testTwo { name: "nameTwo" } 5

SQL Server 2016 get JSONObject from JSONArray using JSONPath

DECLARE #json_str NVARCHAR(MAX) =
'{"Customers":
[{"Id":1,"Name":"Basavaraj",
"Address":{"State":"KA","Country":"India"}},
{"Id":2,"Name":"Kalpana",
"Address":{"State":"NY","Country":"United State"}}
]
}'
SELECT JSON_QUERY(#json_str,'$.Customers[0].Address') AddressObject
If we execute above query it is returning Customers Address object.
AddressObject
{"State":"KA","Country":"India"}
I want get single Customer object according to property like
DECLARE #json_str NVARCHAR(MAX) =
'{"Customers":
[{"Id":1,"Name":"Basavaraj",
"Address":{"State":"KA","Country":"India"}},
{"Id":2,"Name":"Kalpana",
"Address":{"State":"NY","Country":"United State"}}
]
}'
SELECT JSON_QUERY(#json_str,'$.Customers[].State') AddressObject where AddressObject="NY"
AddressObject
{"State":"NY","Country":"United State"}
can we do this in SQL server 2016?