Generate JSON Data from SQL with FOR JSON AUTO

SQL

So I was recently working on a test project and I needed some JSON data. Instead of hooking my application to the SQL Server environment, I created the data from the tables that already existed in SQL.
Using SSMS, I simply appended the following command to my SELECT


FOR JSON AUTO

For example,


SELECT TOP (1000) [VehicleId]
,[Make]
,[Model]
,[Year]
,[Color]
,[Available]
,[CustomerId]
,[Miles]
,[InvoiceId]
,[SalespersonId]
FROM [StithAutoGroupDb].[dbo].[Vehicles]
FOR JSON AUTO

The result

JSON_F52E2B61-18A1-11d1-B105-00805F49916B
[

    {

        "VehicleId": 1,

        "Make": "Toyota",

        "Model": "Camry",

        "Year": 2021,

        "Color": "Blue",

        "Available": true,

        "CustomerId": 3,

        "Miles": ""

    },

    {

        "VehicleId": 2,

        "Make": "Honda",

        "Model": "Civic",

        "Year": 2020,

        "Color": "Black",

        "Available": false,

        "CustomerId": 1,

        "Miles": "55826"

    },

    {

        "VehicleId": 3,

        "Make": "Ford",

        "Model": "F-150",

        "Year": 2022,

        "Color": "Red",

        "Available": true,

        "CustomerId": 4,

        "Miles": ""

    },

    {

        "VehicleId": 4,

        "Make": "Chevrolet",

        "Model": "Malibu",

        "Year": 2019,

        "Color": "White",

        "Available": false,

        "CustomerId": 2,

        "Miles": ""

    },

    {

        "VehicleId": 5,

        "Make": "Tesla",

        "Model": "Model 3",

        "Year": 2023,

        "Color": "Silver",

        "Available": true,

        "CustomerId": 5,

        "Miles": ""

    },

    {

        "VehicleId": 6,

        "Make": "BMW",

        "Model": "iX M70",

        "Year": 2025,

        "Color": "Black",

        "Available": true,

        "CustomerId": 1,

        "Miles": ""

    }

]

That’s it for now. Hope this helps you in your coding journey. Until next time!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *