json - Powershell convertfrom-json |转换为 csv

标签 json powershell csv

我有一个结构如下的 JSON 数据(这里可能有一些错误,我使用的数据很好):

[{
"id": 12345,
"itemName": "some string",
"sellerId": 123,
"seller": "",
"categoryId": ,
"categoryPath": [
  {
   //more data
  },
  {
   //more data
  }
]}, 
{"id": 12346,
"itemName": "some other string",
"sellerId": 234,
"seller": "",
"categoryId": ,
"categoryPath": [
  {
   //more data
  },
  {
   //more data
  }
]
}]

我想将其转换为 csv,以便选定的属性名称成为 csv 标题,并且它们的值(仅深度 1)成为数据。
例如
id,itemName,sellerId
12345,"some string",123
12346,"some other string",234

我试过使用数百种变体
cat file.json | convertfrom-json | convertto-csv

但没有一个工作。我得到的只是带有对象名称/类型的 csv 数据,我不知道如何让它只使用来自 json 数据的每个对象的选定属性。

最佳答案

总之,你需要做这样的事情:

(Get-Content file.json -Raw | ConvertFrom-Json) | Select id,itemName,sellerId | Convertto-CSV -NoTypeInformation

第一个问题是Get-Content正在将单独的行传递给 ConvertFrom-Json这不是它想要的。使用 -Raw switch 完全通过它。
(Get-Content file.json -Raw | ConvertFrom-Json)需要在括号中,因为这允许我们继续使用管道。不这样做就无法访问这些属性。看起来它试图将整个对象而不是它的各个部分传递到管道中。
-NoTypeInformation删除这样的行
#TYPE Selected.System.Management.Automation.PSCustomObject

关于json - Powershell convertfrom-json |转换为 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30485004/

相关文章:

android - 用moshi解析json

PHP mysqli_fetch_assoc() 函数在同一个 PHP 文件工作时返回 NULL

.net - 如何在PowerShell中将字符串内容拆分为字符串数组?

windows - 使用 PowerShell 设置 DNS

python - 高效处理 300 万个 Pandas 数据框行

javascript - 如何将ng-repeat中的数据与不同的索引绑定(bind)

python - 如何在 Django 中将两个带有 html 的变量作为 JSON 发送?

Powershell - 使用参数中包含的括号调用 icacls

python - 将更改应用于同一目录中的多个文件

python - CSV 文件 : Change the position of column to row and reorganize dataset