0

I have a variable with multiple JSON objects.

{
    "Objects":  [
                            {
                                "Name":  "Object 2",
                                "Description":  "This is object 2"
                            },
                            {
                                "Name":  "Object 3",
                                "Description":  "This is object 3"
                            },
}

I want to output those into a HTML table:

NAME | DESCRIPTION

Object ... | Object desc ...

I did the following script:

$convData = $jsonObjects | ConvertTo-Html -Fragment
$htmlTable = @"
    {
        "Title" : "HTML Formatted Table",
        "Description" : "This is a table with JSON Objects<br ><br /> $convData"
    }
"@

$htmlTable

But the output was:

{ "Title" : "HTML Formatted Table", "Description" : "This is a table with JSON
Objects<br /><br />
<table>
  <colgroup>
    <col />
    <col />
    <col />
    <col />
    <col />
    <col />
    <col />
  </colgroup>
  <tr>
    <th>Count</th>
    <th>IsReadOnly</th>
    <th>Keys</th>
    <th>Values</th>
    <th>IsFixedSize</th>
    <th>Sy ncRoot</th>
    <th>IsSynchronized</th>
  </tr>
  <tr>
    <td>1</td>
    <td>False</td>
    <td>
      System.Collections.Specialized.OrderedDictionary+OrderedDictionaryKeyValueCollection
    </td>
    <td>
      System.Collections.Specialized.OrderedDictionary+OrderedDictionaryKe
      yValueCollection
    </td>
    <td>False</td>
    <td>System.Object</td>
    <td>False</td>
  </tr>
</table>
" }

Please, can someone point me in the right direction on how to do this? Thank you...

1
  • 1
    Assuming $jsonObjects is the result of passing the sample json to ConvertFrom-Json: Change $jsonObjects | ConvertTo-Html -Fragment to $jsonObjects.Objects | ConvertTo-Html -Fragment Commented Mar 14, 2022 at 17:11

1 Answer 1

1

This will create a HTML table. In this method you can use all CSS styles in html output file.ConvertTo-Html wont give you such option.

$json = '{
 "Objects":  [
{
"Name":  "Object 2",
"Description":  "This is object 2"
},
{
"Name":  "Object 3",
"Description":  "This is object 3"
}
]}'
$Data=$json|ConvertFrom-Json

#HTML Table header
$html="
<Html>
<Body>
<Table border=1 style='border-collapse: collapse;width:50%;text-align:center'>
<th>Name</th> <th>Description</th> "

#adding HTML table row
foreach($D in $Data.Objects)
{
  $html+= "<tr> <td> $($D.name) </td> <td> $($D.Description) </td></tr>"
}

#Close HTML tags
$html +="</table></body></html>"

#Write data to HTML file
$html >>c:\json.html
Sign up to request clarification or add additional context in comments.

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.