Powershell convertfrom-json | convertto-csv [英] Powershell convertfrom-json | convertto-csv

查看:1515
本文介绍了Powershell convertfrom-json | convertto-csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a JSON data structured as following (there may be some mistakes here, the data I'm using is fine):

[{
"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)成为数据。
eg

I would like to convert it to csv so that the selected property names become csv headers and their value (depth 1 only) become data. e.g

id,itemName,sellerId
12345,"some string",123
12346,"some other string",234

>

I've tried using hundreds of variations of

cat file.json | convertfrom-json | convertto-csv

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

but none have worked. All I get is csv data with objects names/types and I can't figure out how to make it use only selected properties of each object from json data.

推荐答案

简而言之,您需要这样做:

In short you need to do something like this:

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

第一个问题是 Get-Content 将个别行传递到 ConvertFrom-Json ,这不是它想要的。使用 -Raw 开关完整地传递它。

The first problem was that Get-Content was passing individual lines to ConvertFrom-Json which is not what it wants. Using the -Raw switch passes it in its entirety.

需要在括号中的(Get-Content file.json -Raw | ConvertFrom-Json)允许我们继续管道。如果没有这样做,属性是不可访问的。它看起来像是试图传递整个对象,而不是它的单个部分在管道。

The (Get-Content file.json -Raw | ConvertFrom-Json) needs to be in parentheses as that allows us to continue with the pipe. The properties are not accessible without doing this. It looks like it is trying to pass the entire object instead of its individual parts down the pipe.

-NoTypeInformation 删除这样的行

#TYPE Selected.System.Management.Automation.PSCustomObject

这篇关于Powershell convertfrom-json | convertto-csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆