PowerShell Converter | ConvertTo-CSV

I have JSON data structured as follows (there might be some errors here, the data I use 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 } ] }] 

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

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

I tried using hundreds of options

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

but no one worked. All I get is csv data with names / types of objects, and I cannot figure out how to make it use only the selected properties of each object from json data.

+5
source share
1 answer

In short, you need to do something like this:

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

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

In parentheses should be (Get-Content file.json -Raw | ConvertFrom-Json) , as this allows us to continue working with the pipe. Properties are not available without this. It seems that he is trying to transfer the entire object, and not its individual parts down the pipe.

-NoTypeInformation removes such lines

 #TYPE Selected.System.Management.Automation.PSCustomObject 
+8
source

All Articles