0

I have a data table stored in my sql server and i wanna convert it into JSON for creating a chart from the JSON data(using D3JS). but for now I only want to convert sql server data into JSON. suppose my table name is salary (EmpName, Salary) now my query is how to parse this data table into JSON for further use.

3
  • 2
    You would be much better off doing this in your client layer than trying to do it in T-SQL Commented Aug 18, 2014 at 11:55
  • I agree with @AlexK. this could possibly be done with some horrible select queries or some custom sql library but it'd be far more sensible to do it in your BLL. Perhaps some more context would help here? Commented Aug 18, 2014 at 11:57
  • you can convert the data in your client to JSON by using json library james.newtonking.com/json Commented Aug 18, 2014 at 12:10

4 Answers 4

1

One of the top feature of MSSQL server 2016 is built in support of JSON. You can write a very simple query now to Format Query Results as JSON in MSSQL by using FOR JSON in the select statement. Checkout the below example.

Using PATH mode with the FOR JSON Clause

SELECT SalesOrderNumber AS 'Order.Number',
       OrderDate AS 'Order.Date',
       UnitPrice AS 'Product.Price',
       OrderQty AS 'Product.Quantity'
FROM Sales.SalesOrderHeader H
  INNER JOIN Sales.SalesOrderDetail D
    ON H.SalesOrderID = D.SalesOrderID
FOR JSON PATH

Output of FOR JSON with Path mode

[
  {
    "Order":{
        "Number":"SO43659",
        "Date":"2011-05-31T00:00:00"
      },
    "Product":{
         "Price":2024.9940,
         "Quantity":1
     }
  },
  {
    "Order":{ "Number":"SO43659" },
    "Product":{"Price":2024.9940}
  }
]
Sign up to request clarification or add additional context in comments.

Comments

0

SQL Server 2016 has support for JSON for programmers, convert data from SQL to JSON using FOR JSON AUTO and FOR JSON PATH syntax SQL support from JSON to SQL data will be available with release of CTP3

Comments

0

FOR JSON is already available in Sql Server 2016 CTP2 see https://msdn.microsoft.com/en-us/library/dn921882(v=sql.130).aspx

Comments

0

Using MSSLQ SERVER 2016

select
  EmpName as empName, 
  Salary as salary,
from 
 salary
for json path, root('salaries')

returns

{"salaries":[
  {"empName":"John","salary":50000},
  {"empName":"Mary","salary":60000}
]}

If you had to do it useing pre-2016, there are a variety of methods, none of them very good in my opinion.

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.