7

I have a DataTable $dt with same data, I would like to pipe the data to JSON using the cmdlet ConvertTo-JSON in Powershell v3

$ds.Tables["mytable"] | ConvertTo-Json

The result is all the properties of the DataTable are returned, but I only need the records in the data table.

I am wondering if there is a way to do this without looking through each column/ row and adding then into a custom object..etc.

This is what I get when I run the above line;

[
    {
        "RowError":  "",
       "RowState":  2,
        "Table":  {
                  "CaseSensitive":  false,
                  "IsInitialized":  true,
                  "RemotingFormat":  0,
                  "ChildRelations":  "",
                  "Columns":  "Id Name IsActive",
                  "Constraints":  "",
                  "DataSet":  "System.Data.DataSet",
                  "DefaultView":  "System.Data.DataRowView System.Data.DataRowView",
                  "DisplayExpression":  "",
                  "ExtendedProperties":  "System.D.......

Thanks

Yasir

http://www.sqlist.co.uk

1

2 Answers 2

18

After playing with a sample datatable a bit, I ended up with this:

($ds.Tables["mytable"] | select $ds.Tables["mytable"].Columns.ColumnName ) | ConvertTo-Json
Sign up to request clarification or add additional context in comments.

3 Comments

perfect, just an extra )
oh ya this is very helpful. I write my data to JSON files and it looks like this: $JSONFileNameFormat = "C:\thao\nVision\Data\test\Json\{0}.{1}.JSON" $JsonOutputFile = [string]::Format($JSONFileNameFormat, $($Row[0]),$($Row[1])) ($DataSet_Table.Tables[0] | select $DataSet_Table.Tables[0].Columns.ColumnName ) | ConvertTo-Json -Compress | Out-File $JsonOutputFile
I found the essential transform here was: $dt | select $dt.Columns.ColumnName, that is enough to get an array of PS objects with the necessary properties. From there you can iterate, or convert it all at once -- Great answer!
7

You can also exclude properties with Select-Object, removing the noise.

$dt | Select-Object * -ExcludeProperty ItemArray, Table, RowError, RowState, HasErrors | ConvertTo-Json

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.