You should read this if: you are trying to find out how to transform SQL server data into JSON and put it into a text .json file
Question:
Can someone tell me what's wrong with this code? My goal is to read data from a SQL Server table, convert it to JSON and then save the result as a JSON text file. The code runs but the resulting .json file just has:
{
"FieldCount": 11
},
{
repeated over and over again and nothing more.
My code:
$instance = "localhost\SQLEXPRESS"
$connectionString = "Server=$Instance; Database=myDB;Integrated Security=True;"
$query = "Select * from myTable"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $query
$result = $command.ExecuteReader()
$result | ConvertTo-Json | Out-File "file.json"
$connection.Close()
Update:
Will award the answer to postanote as technically he/she answered my original question (although I will caveat and say I have not tried it).
However I would recommend either Mike's answer or what I eventually ended up going with, using BCP:
bcp "select * from myTable FOR JSON AUTO" queryout "C:\filepath\testsml.json" -c -S ".\SQLEXPRESS" -d myDBName -T
- Note that the JSON AUTO will automatically come up with a json scehma for you vs. JSON pipeline which allows you to customize it.
- You have to install BCP first: https://learn.microsoft.com/en-us/sql/tools/bcp-utility?view=sql-server-2017