在SQL中查询JSON

时间:2015-02-24 15:41:55

标签: sql sql-server json tsql

我试图找到一种在SQL中查询JSON的方法,类似于查询XML。有任何想法吗?我还没有保存任何数据,所以我非常开放,尽管我已经阅读了保存JSON的最佳方法是使用varchar(max)列。

由于

示例:

我们假设以下JSON对象存储在varchar(max)列中,我想查询该列,并使用" success" flag = False。

{"TransactionID":"sample string 1","Success":true,
 "Response":"sample string 3","Values":"sample string 4"}

2 个答案:

答案 0 :(得分:0)

故事的道德:不要使用SQL来做到这一点。 CLR和JSON包装器是可行的方法。但如果你真的很好奇,你可以做下面的事情。有很多问题可能会发生,很难列出所有问题。关于该主题的快速谷歌将很容易地说明原因。如果你可以确保完美形成完美的JSON对象,这可能是你可以研究的东西。也许。不要使用它。

/*
JSON to XML Parser TSQL
Compatibility: TEsted on SQL Server 2014
Assumptions:    -Perfectly formed JSON as declared below.
                -Charecters for formatting are ok but will be removed
*/

--Imagine @JSONDATA would be the parameter to your function
DECLARE @JSONDATA VARCHAR(MAX) = '{"transactions":[
                                        {"TransacitonID":"transaction1","Success":true,"Response":"sample string 1","Values":"sample string 1"},
                                        {"TransactionID":"transaction2","Success":false,"Response":"sample string 2","Values":"sample string 2"}
                                ]}'

DECLARE @ObjectArrayNameStart INT
DECLARE @ObjectArrayNameEnd INT
DECLARE @ObjectArray VARCHAR(MAX)
DECLARE @ObjectArrayName VARCHAR(MAX)
DECLARE @ObjectArrayBracketStart INT
DECLARE @ObjectArrayBracketEnd INT
DECLARE @ObjectArraySingleton VARCHAR(MAX)
DECLARE @ObjectXML XML



--Replace All CR and LF charecters and HT chars
SET @JSONDATA = REPLACE(REPLACE(REPLACE(@JSONDATA,CHAR(10),''),CHAR(13),''),CHAR(9),'') --LF

--Get the ObjectArrayName
SELECT @ObjectArrayNameStart = PATINDEX('%{["]transactions["]:[[]%',@JSONDATA), @ObjectArrayNameEnd = PATINdEX('%[[]%',@JSONDATA)
SET @ObjectArrayName = SUBSTRING(@JSONDATA,@ObjectArrayNameStart,@ObjectArrayNameEnd)

--Get the ObjectArray name
SET @ObjectArray = REPLACE(@JSONDATA,@ObjectArrayName,'')

----Trim out the word of the object array and get the single word and singleton item
SET @ObjectArrayName = LEFT(@ObjectArrayName,@ObjectArrayNameEnd - 3)
SET @ObjectArrayName = RIGHT(@ObjectArrayName, LEN(@ObjectArrayName) - 2)
SET @ObjectArraySingleton = 'node'

--PREP THE JSON OBJECT DOWN TO INDIVIDUAL OBJECTS AND SET AS XML DOCUMENT
SET @ObjectArray = LTRIM(RTRIM(REPLACE(@ObjectArray,']}','')))
SET @ObjectArray = REPLACE(@ObjectArray,'},{','</' + @ObjectArraySingleton + '><' + @ObjectArraySingleton + '>')
SET @ObjectArray = REPLACE(@ObjectArray,'{','<' + @ObjectArraySingleton + '>')
SET @ObjectArray = REPLACE(@ObjectArray,'}','</' + @ObjectArraySingleton + '>')
SET @ObjectArray = '<root>' + @ObjectArray + '</root>'
SET @ObjectXML =  CAST(@ObjectArray AS XML)

--Query for line data
;WITH XMLObjectData AS (
    SELECT  Item.value('text()[1]','nvarchar(max)') AS ObjectLine
    FROM    @ObjectXML.nodes('/root/node') AS Items(Item)
), CommaSplit AS (
    SELECT  '<pair><key>' + REPLACE(X.ObjectLine,',','</value></pair><pair><key>') + '</value></pair>' AS ObjectLine
    FROM    XMLObjectData AS X
), ColonSplit AS (
    SELECT  REPLACE(X.ObjectLine,':','</key><value>') AS ObjectLine
    FROM    CommaSplit AS X
), QuoteReplace AS (
    SELECT  REPLACE(X.ObjectLine,'"','') AS ObjectLine
    FROM    ColonSplit AS X
)
SELECT  CAST(F.ObjectLine AS XML)
FROM    QuoteReplace AS F
FOR     XML PATH('object'), ROOT('root')


--COMMENTED OUT FOR TESTING
--SELECT    @JSONDATA AS JSONData, 
--      @ObjectArrayName AS ObjArrayName, 
--      @ObjectArrayNameStart AS ObjArrayNameStart, 
--      @ObjectArrayNameEnd AS ObjArrayNameEnd,
--      @ObjectArray AS ObjArray,
--      @ObjectArraySingleton AS ObjSingleton
--      --,CAST(@ObjectArray AS XML) AS XMLObjectArray

答案 1 :(得分:0)

    select ca.TransactionID, ca.Success, ca.Response, cs.Values from 
    table_name tn with(NOLOCK)
    CROSS APPLY(select * from OPENJSON(tn.JSONColumnName) WITH(
    [TransactionID] nvarchar(50) '$.TransactionID',
    [Success] bit '$,Success',
    [Response] nvarchar(50), '$.Response',
    [Values] nvarchar(50) '$.Values'
    )) ca
    Where ca.Success = 0