简体   繁体   English

使用powershell将csv转换为json

[英]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我有一个 csv 文件,当我使用 convertto-json 转换它时,出现以下错误

ConvertTo-Json : The converted JSON string is in bad format. ConvertTo-Json :转换后的 JSON 字符串格式错误。 At line:1 char:70 + Get-Content -path E:\\test.csv |在 line:1 char:70 + Get-Content -path E:\\test.csv | ConvertFrom-Csv -Delimiter ',' | ConvertFrom-Csv -Delimiter ',' | ConvertTo-J ... + ~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (@{name=WebError.Show; data=1}:PSObject) [ConvertTo-Json], InvalidOperationException + FullyQualifiedErrorId : JsonStringInBadFormat,Microsoft.PowerShell.Commands.ConvertToJsonCommand 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当我将 -compress 与 convertto-json 一起使用时,我得到了输出,但它是一个很难看的压缩 json 版本,是否有更好的方法将此 csv 转换为 json 或有没有办法解压缩 json

CSV: CSV:

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

Compressed Json Output:压缩的 Json 输出:

[{"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. 在您的示例字符串中使用ConvertFrom-Csv和ConvertTo-Json似乎没有任何问题。

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? 您能发布会给您错误的PowerShell代码吗?

Import-Csv $File | Convertto-Json

这可能对您有用。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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