创建带有转义字符的二维数组

Creating a 2D Array with escaped characters

我有一个 CSV,我们称它为 test.csv

"country","city","population","remarks"
"germany","munih","1472000","i am a 
line
brake"
"italy","rome","2873000","<>|'"
"spain","madrid","6642000","!"§$%&/("

我需要一个完整的 HTML 转义 2D JS-array 没有 headers 并且名称如下:

"germany","munih","1472000","i am a \nline\nbrake"

分别是:

var MyVar = [["germany","munih","1472000","i am a \nline\nbrake"],["italy","rome","2873000","&lt;&gt;|&#39;"],["spain","madrid","6642000","!&#167;$%&amp;/(&quot;"]];

ConvertTo-Json 可以逃脱,但没有找到任何简单的方法来生成没有 Object 名称的二维数组:

Import-Csv ".\test.csv" | ConvertTo-Json -EscapeHandling EscapeHtml
[
  {
    "country": "germany",
    "city": "munih",
    "population": "1472000",
    "remarks": "i am a \r\nline\r\nbrake"
  },
  {
    "country": "italy",
    "city": "rome",
    "population": "2873000",
    "remarks": "\u003c\u003e|\u0027"
  },
  {
    "country": "spain",
    "city": "madrid",
    "population": "6642000",
    "remarks": "!§$%\u0026/(\u0022"
  }
]

ConverTo-CSV做的不错,就是逃不掉:

Import-Csv ".\test.csv" | ConvertTo-Csv -UseQuotes Always
"country","city","population","remarks"
"germany","munih","1472000","i am a 
line
brake"
"italy","rome","2873000","<>|'"
"spain","madrid","6642000","!§$%&/("""

以下例行工作。但我相信,一定有更简单的方法。

$t1 = Import-Csv ".\test.csv"

$arr_len = $t1.Count
$obj_len = $t1[0].Psobject.Properties.value.count

$str_builder = [System.Text.StringBuilder]::new()
for ($i=0; $i -lt $arr_len; $i++){
    #first outer loop
    if ($i -eq 0){[void]$str_builder.Append('var MyVar = [')}

    for ($j=0; $j -lt $obj_len; $j++){
        #first inner loop
        if ($j -eq 0){[void]$str_builder.Append('[')}
        
        #$t1[$i].Psobject.Properties.Name[$j]
        $each = $t1[$i].Psobject.Properties.Value[$j]
        $each_esc = ([System.Net.WebUtility]::HtmlEncode($each)) -replace("`r`n|`r|'n","\n")
        [void]$str_builder.Append('"')
        [void]$str_builder.Append($each_esc)
        [void]$str_builder.Append('"')
        
        #last inner loop
        if ($j -eq ($obj_len-1)){
            if ($i -ne ($arr_len-1)){
                [void]$str_builder.Append('],')
            } else {
                [void]$str_builder.Append(']')
            }
        } else{
            [void]$str_builder.Append(',')
        }
     
    }
    
    #last outer loop
    if ($i -eq ($arr_len-1)){[void]$str_builder.Append('];')}
}

$final = $str_builder.ToString()
[void]$str_builder.Clear()

有什么提示、想法吗?谢谢 :)

从给定的输入不可能产生所需的输出。

您必须先创建嵌套列表,然后是 json 文档。

尝试以下操作:

$list = [System.Collections.Generic.List[psobject]]::new()
foreach($item in $input) {
    $nestedList = [System.Collections.Generic.List[string]]::new()

    $itemProps = $item.psobject.properties
    foreach($itemProp in $itemProps) {
        $nestedList.Add($itemProp.Value)
    }
    $list.Add($nestedList)
}

$list | ConvertTo-Json -EscapeHandling EscapeHtml
<#
$PSVersionTable.PSVersion
Major  Minor  Patch  PreReleaseLabel BuildLabel
-----  -----  -----  --------------- ----------
7      1      0
#>
$fieldsCount = 4
$rawText = @'
"country","city","population","remarks"
"germany","munih","1472000","i am a 
line
brake"
"italy","rome","2873000","<>|'"
"spain","madrid","6642000","!"§$%&/("
'@ 

$rawArray = $rawText.Trim("`"") -split "`r`n" -join "," -split '","' 
$table = $(for ($i = $fieldsCount; $i -lt $rawArray.Count; $i += $fieldsCount){
   [PSCustomObject]@{
      country = $rawArray[$i]
      city = $rawArray[$i+1]
      population = $rawArray[$i+2]
      remarks = $rawArray[$i+3]
   }   
})

$table | ConvertTo-Json

<#
country city   population remarks
------- ----   ---------- -------
germany munih  1472000    i am a ,line,brake
italy   rome   2873000    <>|'
spain   madrid 6642000    !"§$%&/(

 [
  {
    "country": "germany",
    "city": "munih",
    "population": "1472000",
    "remarks": "i am a ,line,brake"
  },
  {
    "country": "italy",
    "city": "rome",
    "population": "2873000",
    "remarks": "<>|'"
  },
  {
    "country": "spain",
    "city": "madrid",
    "population": "6642000",
    "remarks": "!\"§$%&/("
  }
]
#>

您可以像这样简化代码:

Add-Type -AssemblyName System.Web

$data   = Import-Csv -Path 'D:\Test\test.csv'

$jsData = foreach ($item in $data) {
 # create an array of quoted encoded strings
 $values = $item.PsObject.Properties.Value | ForEach-Object {
    '"{0}"' -f [System.Web.HttpUtility]::HtmlEncode(($_ -replace '\r?\n', '\n'))
 }
 # output the encoded strings grouped inside square brackets
 '[{0}]' -f ($values -join ',')
}

# combine the resulting data into a 2D array
$result = 'var MyVar = [{0}];' -f ($jsData -join ',')

$result

输出:

var MyVar = [["germany","munih","1472000","i am a \nline\nbrake"],["italy","rome","2873000","&lt;&gt;|&#39;"],["spain","madrid","6642000","!&#167;$%&amp;/(&quot;"]];