简体   繁体   中英

Store json file in MS SQL

I have a JSON file, how to store a JSON file in MS SQL? And read the file data after storing it into Database?

I'm using a python script to interact with SQL Server.

Note: I don't want to store key-value pairs as an individual records in DB, I want to store the whole file in DB using python.

There is no specific data type for JSON in SQL Server, unlike say XML which has the xml data type.

If you are, however, storing JSON data in SQL Server then you will want to use an nvarchar(MAX) . If you are on SQL Server 2016+ I also recommend adding a CHECK CONSTRAINT to the column to ensure that the JSON is valid, as otherwise parsing it (in SQL) will be impossible. You can check if a value is valid JSON using ISJSON . For example, if you were adding the column to an existing table:

ALTER TABLE dbo.YourTable ADD YourJSON nvarchar(MAX) NULL;
GO
ALTER TABLE dbo.YourTable ADD CONSTRAINT chk_YourTable_ValidJSON CHECK (ISJSON(YourJSON) = 1 OR YourJSON IS NULL);

SQL server has a JSON data type for this. This is wrong.

If your version doesn't, you can just store it as a string with VARCHAR or TEXT .

This article reckons NVARCHAR(max) is the answer for documents greater than 8KB, for documents under that you can use NVARCHAR(4000) which apparently has better performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM