首页 > 解决方案 > Powershell JSON 对象到 HTML 表并将其添加到另一个 JSON 对象的值

问题描述

我有以下动态创建的 JSON 对象,可以在名称中包含特殊字符,例如姓氏中的 O'Brian 和 Notes 中的特殊字符。

$jsonData = @"
{
        "ReqId": 37,
        "First Name": "John",
        "Middle Name": "",
        "Last Name": "O'Brian",
        "Preferred Name": "John",
        "Date": "04/28/2021 05:00:00",
        "Email": "test@xyz.com",
        "Notes": "This is a note with Special characters"
}
"@ | ConvertTo-Json;

我想使用这个 JSON 数据并将其转换为 HTML 表格格式。然后将此 HTML 数据作为另一个 JSON 对象中的键值传递,然后将其发送到 API。

$convData = ConvertTo-Html -InputObject ($jsonData);
$apiJson = @"
    {
        "Title" : "This is Test",
        "Description" : "This is Test Description.<br ><br /> $convData"
    }
    "@

$apiJson 需要是有效的 JSON,以便 API 可以成功地将其解析为 JSON 对象。

我尝试了 ConvertTo-HTML 方法,但它不起作用并给出了空表。我也想要<table>...</table>一部分,需要删除其他标签。

{
    "Test" : "This is Test",
    "description" : "This is Test.<br > <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//E
N"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/x
html"> <head> <title>HTML TABLE</title> </head><body> <table> <colgroup><col/></colgroup> <tr>
<th>*</th></tr> <tr><td>539</td></tr> </table> </body></html>"
}

需要帮忙。谢谢你。

标签: htmljsonpowershell

解决方案


  1. 更改ConvertTo-JsonConvertFrom-Json- 您想要将 json 转换为可以转换为 html 表的对象

  2. -Fragment开关添加到ConvertTo-Html以仅生成 HTML 表

_

$jsonData = @'
{
        "ReqId": 37,
        "First Name": "John",
        "Middle Name": "",
        "Last Name": "O'Brian",
        "Preferred Name": "John",
        "Date": "04/28/2021 05:00:00",
        "Email": "test@xyz.com",
        "Notes": "This is a note with Special characters"
}
'@ | ConvertFrom-Json

$convData = $jsonData | ConvertTo-Html -Fragment
$apiJson = @"
    {
        "Title" : "This is Test",
        "Description" : "This is Test Description.<br ><br /> $convData"
    }
"@

推荐阅读