9

I'm aware of the option to output a query formatted as JSON, like the following example from the from MSDN page:

SELECT name, surname  
FROM emp  
FOR JSON AUTO 

There are a lot of samples on how to use the resulting json from apps but my question is, how can I store the resulting json in a varchar variable, let's say to store in another table?

2
  • Note that FOR JSON AUTO only applies to SQL Server 2016+ Commented Mar 14, 2018 at 4:07
  • Also applies to SQL Azure. Commented Mar 15, 2018 at 9:30

3 Answers 3

17
DECLARE @Json nvarchar(MAX) = (
    SELECT name, surname  
    FROM emp  
    FOR JSON AUTO
);

Dan Guzman replied in the MSDN Forum with this neat solution, which corresponds also to @FDavidov's suggestion in his last comment

Sign up to request clarification or add additional context in comments.

Comments

1

A JSON is, in fact, a character string. What makes this character string to be a JSON is the combination of two things:

  1. You refer to it as a JSON (using the correct functions within your environment),
  2. It contains the correct delimiters at the correct locations to comply with the rules of a JSON.

So, if you want to store a JSON in a variable, just assign to the variable the source string and, whenever you want to act on your variable, just remember it is a JSON.

5 Comments

My question is not about json itself, but how can you store the output of a "FOR JSON" query, which returns a json string as you described, in a local variable.
Dear @AlbertoSilva, what you have shown is a pretty-printing of the JSON, also a string with tabs/blanks and new-line chats. If I'm still missing what you are asking, you may consider rephrasing.
I'm assuming that you have already used the "FOR JSON" clause from SQL Server 2016/Azure using the query window from SSMS, so you know that the returned json is displayed in the results windows. What I need is to have that json string to be stored in a varchar variable. This doesn't make much sense, but suppose that, using plain t-sql, you want to know the length of the json returned from the above query which may return the following json... [ { "name": "John" }, { "name": "Jane", "surname": "Doe" } ] ...how would you do it?
Well, no, I haven't used it in SQL Server. Here is the point: The result of "FOR JSON" is a prettified version of the JSON which includes blanks and line ends. Measuring the length of it would NOT give you the length of the JSON but the length of its prettified version. To get the length of the JSON, simply measure the length of your original variable. Still, if you want to store the prettified version and its length, there should be a function that returns the prettified version (also a string) from which you can also measure the length.
One more thing: From here you can learn that using FOR JSON n a select would return JSON-formatted results. Try setting a variable as SET x = SELECT * FROM <your-JSON> FOR JSON. (not sure what the result would be though).
0

I was looking for a similar thing, but how to use the JSON PATH output data from SQL Server in an application. In this case, in Node.JS (although this concept would be adaptable to other languages). Here's a sample of what I came up with:

var {recordset} = await new sql.Request(primary.dbPool)
.input('primaryID', sql.UniqueIdentifier, primaryID)
.query(`SELECT (
    SELECT MainTable.*,
        (
            SELECT SubTable.* 
            FROM dbo.SubTable AS SubTable WHERE MainTable.Main_RecordID = SubTable.SubTable_Main_RecordID 
            FOR JSON PATH
        ) AS [subItems]
    FROM dbo.MainTable AS MainTable
    WHERE primaryID = @primaryID
    FOR JSON PATH, ROOT('mainItems')
) AS jsonResult;`)
let mainItems = JSON.parse(recordset[0].jsonResult).mainItems

console.log(mainItems)

This avoids it being returned as a long string in a UUID field like: UUID

And is instead something you can use in the application.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.