【问题标题】:Convert a JSON representation of CSV data to actual CSV data将 CSV 数据的 JSON 表示形式转换为实际的 CSV 数据
【发布时间】:2021-11-15 10:59:16
【问题描述】:

这个自我回答的问题是关于将 CSV 数据的 JSON 表示形式转换为实际的 CSV 数据。[1]

以下 JSON 包含单独的属性,分别描述标题(列名)(columns)和相应行值的数组(rows):

{
  "columns": [
      {
          "name": "ColumnName1",
          "type": "Number"
      },
      {
          "name": "ColumnName2",
          "type": "String"
      },
      {
          "name": "ColumnName3",
          "type": "String"
      }
  ],
  "rows":    [
      [
          11111,
          "ResourceType1",
          "String1"
      ],
      [
          22222,
          "ResourceType2",
          "String2"
      ],
      [
          33333,
          "ResourceType3",
          "String3"
      ]
  ]
}

如何将此 JSON 输入转换为它所代表的 CSV 数据?


[1] 该问题与this closed question 重复,这可能是由于缺乏努力而被关闭,即使它要求的内容已经相当明确。

【问题讨论】:

    标签: json powershell csv


    【解决方案1】:

    请注意,CSV 文件没有数据类型的概念——所有值都是字符串, 所以数据类型信息(来自.column.type 属性)会丢失,除非您选择合并它 以某种方式作为 CSV 的消费者必须了解的约定

    假设问题中的 JSON 保存在文件 file.json 中,通过读取文件 as text 可以使用 ConvertFrom-Json 将其解析为 ([pscustomobject]) 对象图Get-Content:

    # Convert the JSON text into a [pscustomobject] object graph.
    $fromJson = ConvertFrom-Json (Get-Content -Raw file.json)
    
    # Process the array of column names and the arrays of row values by
    # enclosing the array elements in "..." and joining them with ","
    (, $fromJson.Columns.Name + $fromJson.Rows).ForEach({
      $_.ForEach({ '"{0}"' -f ($_ -replace '"', '""') }) -join ','
    })
    

    请注意,上面将列名和值括在"..." 中,以便也支持 嵌入 , 字符的名称和值;此外,任何嵌入的" 字符都可以通过加倍正确转义。

    如果您知道输入数据既不包含嵌入 , 的值也不包含 ",可以直接省略内部的.ForEach() array method 上面调用,这将导致 unquoted 值。

    以上输出:

    "ColumnName1","ColumnName2","ColumnName3"
    "11111","ResourceType1","String1"
    "22222","ResourceType2","String2"
    "33333","ResourceType3","String3"
    
    • 要将上述内存中转换为代表CSV数据的([pscustomobject])对象,请使用ConvertFrom-Csv...代表上述命令):

      ... | ConvertFrom-Csv
      
    • 要将以上内容保存到 CSV 文件,请使用 Set-Content:

      ... | Set-Content -Encoding utf8 out.csv
      

    【讨论】:

      猜你喜欢
      • 2017-05-27
      • 2023-03-03
      • 1970-01-01
      • 2019-03-09
      • 2015-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多