Code Monkey home page Code Monkey logo

sqlclrjsonparser's Introduction

SqlClrJsonParser

A SQL Server CLR wrapper written in C#, for parsing Json documents within SQL Server versions pre-2016 (before the introduction of OPENJSON and JSON_VALUE functions and such).

Pre-requisites

Most of the pre-requisites are automatically handled by the Pre-Deployment script:

exec sp_configure 'clr enabled', 1
reconfigure
GO
DECLARE @cmd NVARCHAR(MAX)
SELECT @cmd = N'ALTER AUTHORIZATION ON DATABASE::' + QUOTENAME(DB_NAME()) + N' TO ' + QUOTENAME(sp.name)
FROM sys.databases AS db
INNER JOIN sys.server_principals AS sp
ON db.owner_sid = sp.sid
WHERE db.database_id = 1
GO
IF NOT EXISTS (SELECT * FROM sys.assemblies WHERE name = 'System_Runtime_Serialization')
	CREATE ASSEMBLY System_Runtime_Serialization FROM 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Runtime.Serialization.dll'
	WITH PERMISSION_SET = UNSAFE
GO
IF NOT EXISTS (SELECT * FROM sys.assemblies WHERE name = 'Newtonsoft.Json')
	CREATE ASSEMBLY [Newtonsoft.Json]
	FROM '$(PathToNewtonsoftJsonDLL)'
	WITH PERMISSION_SET = UNSAFE
GO

These requirements are:

  • 'clr enabled' instance option must be turned on
  • Target Database must have the same owner as that of the "master" database (usually it's "sa").
  • Target Database must have the TRUSTWORTHY ON setting (already configured in the project settings).
  • The System.Runtime.Serialization assembly must be imported into the database.
  • The Newtonsoft.Json DLL file must be imported into the database (it's already included with the project, you just need to specify the SQLCMD parameter that defines its file path location).

Example Usage

Here is an example usage of this assembly within T-SQL:

DECLARE
	@Json NVARCHAR(MAX) = '{ "result": { "tickets": [ { "id": "123", "name": "hi there" }, { "id": "456", "name": "hello there" } ], "count": "2" } }'

SELECT *
, dbo.JsonValue([value], '$.id') AS [id]
, dbo.JsonValue([value], '$.name') AS [name]
FROM dbo.JsonTable(@Json, '$.result.tickets')

/* Equivalent of:
SELECT *
, JSON_VALUE([value], '$.id') AS [id]
, JSON_VALUE([value], '$.name') AS [name]
FROM OPENJSON (@Json, '$.result.tickets')
*/

Missing Features

As of right now, the following features are still missing:

  • Equivalent of JSON_MODIFY
  • Equivalent of JSON_QUERY
  • Equivalent of FOR JSON (i.e. format a query as a JSON document)

Please see the GitHub Issues page for more info.

sqlclrjsonparser's People

Contributors

eitanblumin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

sqlclrjsonparser's Issues

Implement equivalent of JSON_QUERY

Syntax

JSON_QUERY ( expression [ , path ] )

Arguments

expression
An expression. Typically the name of a variable or a column that contains JSON text.

If JSON_QUERY finds JSON that is not valid in expression before it finds the value identified by path, the function returns an error. If JSON_QUERY doesn't find the value identified by path, it scans the entire text and returns an error if it finds JSON that is not valid anywhere in expression.

path
A JSON path that specifies the object or the array to extract.

In SQL Server 2017 (14.x) and in Azure SQL Database, you can provide a variable as the value of path.

The JSON path can specify lax or strict mode for parsing. If you don't specify the parsing mode, lax mode is the default. For more info, see JSON Path Expressions (SQL Server).

The default value for path is '$'. As a result, if you don't provide a value for path, JSON_QUERY returns the input expression.

If the format of path isn't valid, JSON_QUERY returns an error.

Return value

Returns a JSON fragment of type nvarchar(max). The collation of the returned value is the same as the collation of the input expression.

If the value is not an object or an array:

In lax mode, JSON_QUERY returns null.

In strict mode, JSON_QUERY returns an error.

Remarks

Lax mode and strict mode

The following table compares the behavior of JSON_QUERY in lax mode and in strict mode. For more info about the optional path mode specification (lax or strict), see JSON Path Expressions (SQL Server).

Path Return value in lax mode Return value in strict mode More info
$ Returns the entire JSON text. Returns the entire JSON text. N/a
$.info.type NULL Error Not an object or array.Use JSON_VALUEinstead.
$.info.address.town NULL Error Not an object or array.Use JSON_VALUEinstead.
$.info."address" N'{ "town":"Bristol", "county":"Avon", "country":"England" }' N'{ "town":"Bristol", "county":"Avon", "country":"England" }' N/a
$.info.tags N'[ "Sport", "Water polo"]' N'[ "Sport", "Water polo"]' N/a
$.info.type[0] NULL Error Not an array.
$.info.none NULL Error Property does not exist.

Using JSON_QUERY with FOR JSON

JSON_QUERY returns a valid JSON fragment. As a result, FOR JSON doesn't escape special characters in the JSON_QUERY return value.

If you're returning results with FOR JSON, and you're including data that's already in JSON format (in a column or as the result of an expression), wrap the JSON data with JSON_QUERY without the path parameter.

Source: JSON_QUERY (Transact-SQL)

Implement equivalent of JSON_MODIFY

Syntax

JSON_MODIFY ( expression , path , newValue )

Arguments

expression
An expression. Typically the name of a variable or a column that contains JSON text.

JSON_MODIFY returns an error if expression doesn't contain valid JSON.

path
A JSON path expression that specifies the property to update.

path has the following syntax:

[append] [ lax | strict ] $.<json path>

append
Optional modifier that specifies that the new value should be appended to the array referenced by .

lax
Specifies that the property referenced by does not have to exist. If the property is not present, JSON_MODIFY tries to insert the new value on the specified path. Insertion may fail if the property can't be inserted on the path. If you don't specify lax or strict, lax is the default mode.

strict
Specifies that the property referenced by must be in the JSON expression. If the property is not present, JSON_MODIFY returns an error.

<json path>
Specifies the path for the property to update. For more info, see JSON Path Expressions (SQL Server).

In SQL Server 2017 (14.x) and in Azure SQL Database, you can provide a variable as the value of path.

JSON_MODIFY returns an error if the format of path isn't valid.

newValue
The new value for the property specified by path.

In lax mode, JSON_MODIFY deletes the specified key if the new value is NULL.

JSON_MODIFY escapes all special characters in the new value if the type of the value is NVARCHAR or VARCHAR. A text value is not escaped if it is properly formatted JSON produced by FOR JSON, JSON_QUERY, or JSON_MODIFY.

Return Value

Returns the updated value of expression as properly formatted JSON text.

Remarks

The JSON_MODIFY function lets you either update the value of an existing property, insert a new key:value pair, or delete a key based on a combination of modes and provided values.

The following table compares the behavior of JSON_MODIFY in lax mode and in strict mode. For more info about the optional path mode specification (lax or strict), see JSON Path Expressions (SQL Server).

Existing value Path exists Lax mode Strict mode
Not NULL Yes Update the existing value. Update the existing value.
Not NULL No Try to create a new key:value pair on the specified path.This may fail. For example, if you specify the path $.user.setting.theme, JSON_MODIFY does not insert the key theme if the $.user or $.user.settings objects do not exist, or if settings is an array or a scalar value. Error - INVALID_PROPERTY
NULL Yes Delete the existing property. Set the existing value to null.
NULL No No action. The first argument is returned as the result. Error - INVALID_PROPERTY

Source: JSON_MODIFY (Transact-SQL).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.