简体   繁体   中英

Convert csv to json using powershell

I have a csv file and when I convert it using convertto-json i am getting the following error

ConvertTo-Json : The converted JSON string is in bad format. At line:1 char:70 + Get-Content -path E:\\test.csv | ConvertFrom-Csv -Delimiter ',' | ConvertTo-J ... + ~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (@{name=WebError.Show; data=1}:PSObject) [ConvertTo-Json], InvalidOperationException + FullyQualifiedErrorId : JsonStringInBadFormat,Microsoft.PowerShell.Commands.ConvertToJsonCommand

when i use -compress with convertto-json i am getting the output, but its a compressed json version which is ugly to see, is there a better way to convert this csv to json or is there a way to decompress the json

CSV:

name,data
Play,http://{gho}.domain.com/
BDomain,domain.com
Charts,2
Compress,0
CompressJ,0
WebError.Show,1

Compressed Json Output:

[{"name":"Play","data":"http://{gho}.domain.com/"},{"name":"BDomain","data":"domain.com"},{"name":"Charts","data":"2"},{"name":"Compress","data":"0"},{"name":"CompressJ"
,"data":"0"}]

I don't seem to have any issues using ConvertFrom-Csv and ConvertTo-Json with your example string.

Using:

"name,data
Play,http://{gho}.domain.com/
BDomain,domain.com
Charts,2
Compress,0
CompressJ,0" | ConvertFrom-Csv | ConvertTo-Json

Gives me:

[
    {
        "name":  "Play",
        "data":  "http://{gho}.domain.com/"
    },
    {
        "name":  "BDomain",
        "data":  "domain.com"
    },
    {
        "name":  "Charts",
        "data":  "2"
    },
    {
        "name":  "Compress",
        "data":  "0"
    },
    {
        "name":  "CompressJ",
        "data":  "0"
    }
]

Could you post the PowerShell code which is giving you the error?

Import-Csv $File | Convertto-Json

这可能对您有用。

下面的 Powershell 命令从INPUTFILE.csv文件格式创建OUTPUTFILE.json格式文件:

import-csv .\INPUTFILE.csv | ConvertTo-Json -depth 100 | Out-File .\OUTPUTFILE.json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM