使用PowerShell将CSV转换为JSON和将JSON转换为CSV [英] Convert CSV to JSON and JSON to CSV using PowerShell

查看:341
本文介绍了使用PowerShell将CSV转换为JSON和将JSON转换为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CSV文件,我正在尝试使用PowerShell将其转换为JSON.

I have a CSV file that I am trying to convert to JSON using PowerShell.

CSV文件包含以下数据.

The CSV file contains the following data.

web_url.csv

wikipedia,https://en.wikipedia.org/wiki/%s
wolframalpha,http://www.wolframalpha.com/input/?i=%s
drive,http://www.drive.google.com/

我想以以下格式转换为json.同样,您如何以上述格式将json转换回原始csv?

I would like to convert to json in the following format. Similarly how do you convert this json back to original csv in the format shown above?

web_url.json

{
    "wikipedia": "https://en.wikipedia.org/wiki/%s",
    "wolframalpha": "http://www.wolframalpha.com/input/?i=%s",
    "drive": "http://www.drive.google.com/"
}

当我运行命令时,

获取内容-path web_url.csv | ConvertFrom-Csv-分隔符','| ConvertTo-Json

Get-Content -path web_url.csv | ConvertFrom-Csv -Delimiter ',' | ConvertTo-Json

它返回以下输出,这不是我想要的.

it returns the following output which is not what I want.

[
    {
        "wikipedia":  "wolframalpha",
        "https://en.wikipedia.org/wiki/%s":  "http://www.wolframalpha.com/input/?i=%s"
    },
    {
        "wikipedia":  "drive",
        "https://en.wikipedia.org/wiki/%s":  "http://www.drive.google.com/"
    }
]

推荐答案

对我来说,您的csv看起来不像是适当的" csv:列与行交换.如果您可以控制输入文件,则可以在那里进行修复:

Your csv doen't look like a "proper" csv to me: columns are swapped with rows. If you have control over input file, you may fix it there already:

@'
wikipedia,wolframalpha,drive
https://en.wikipedia.org/wiki/%s,http://www.wolframalpha.com/input/?i=%s,http://www.drive.google.com/
'@ | ConvertFrom-Csv | ConvertTo-Json

如果这不可能,那么您只需执行一些额外的步骤即可获得所需的内容:

If that is not possible, you just have to perform some extra steps to get what you need:

$propertyList = @'
wikipedia,https://en.wikipedia.org/wiki/%s
wolframalpha,http://www.wolframalpha.com/input/?i=%s
drive,http://www.drive.google.com/
'@ | ConvertFrom-Csv -Header Name, Value

$properties = [ordered]@{}

foreach ($property in $propertyList) {
    $properties.Add($property.Name, $property.Value)
}

New-Object PSObject -Property $properties | ConvertTo-Json

再次返回-需要做一些额外的工作:

And back, again - some extra work is required:

(@'
{
    "wikipedia":  "https://en.wikipedia.org/wiki/%s",
    "wolframalpha":  "http://www.wolframalpha.com/input/?i=%s",
    "drive":  "http://www.drive.google.com/"
}
'@ | ConvertFrom-Json).PSObject.Properties |
    Select-Object Name, Value |
    ConvertTo-Csv -NoTypeInformation |
    Select-Object -Skip 1

这篇关于使用PowerShell将CSV转换为JSON和将JSON转换为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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