Windows PowerShell JSON到CSV“System.Object []”问题

时间:2018-05-04 14:45:41

标签: json powershell csv

我一直在努力将JSON文件转换为CSV 3天。不幸的是,我对powershell不太熟悉,任何帮助都会受到赞赏。这是JSON字符串:

ConvertFrom-JSON (Get-Content 'path.json' -Raw) |
    ConvertTo-Csv -NoTypeInformation |
    Select-Object -Skip 1 |
    Set-Content 'path.csv'

Get-Content 'path.json' -Raw |
    ConvertFrom-Json |
    Select -Expand inputFile |
    ForEach {$_.inputFile = $_.inputFile -join ' '$_} |
    Export-Csv 'path.csv' -NoTypeInformation

我尝试过的命令行:

@Component
class JwtAuthenticationConverter : Function<ServerWebExchange, 
Mono<Authentication>> {

@Autowired
lateinit var jwtTokenUtil: JwtTokenUtil

@Autowired
lateinit var userDetailsService: ReactiveUserDetailsService

private val log = LogFactory.getLog(this::class.java)

override fun apply(exchange: ServerWebExchange): Mono<Authentication> {
    val request = exchange.request

    val token = getJwtFromRequest(request)

    if ( token != null )
        try {
            return userDetailsService.findByUsername(jwtTokenUtil.getUsernameFromToken(token))
                    .map { UsernamePasswordAuthenticationToken(it, null, it.authorities) }
        } catch ( e: Exception ) {
            exchange.response.statusCode = HttpStatus.UNAUTHORIZED
            exchange.response.headers["internal-message"] = e.message
            log.error(e)
        }

    return Mono.empty()
}

private fun getJwtFromRequest(request: ServerHttpRequest): String? {
    val bearerToken = request.headers[SecurityConstants.TOKEN_HEADER]?.first {
        it.startsWith(SecurityConstants.TOKEN_PREFIX, true)}
    return if (bearerToken.isNullOrBlank()) null else bearerToken?.substring(7, bearerToken.length)
}

没什么......

我希望得到一个CSV文件:

Column1, Column2, Column3, etc.
A,B,C,etc.

我可以使用哪些命令组合来执行此操作?

2 个答案:

答案 0 :(得分:3)

Export-Csv期望一个对象列表作为输入。对象的属性(由第一个对象的属性标识)将导出为CSV列。要使cmdlet按预期方式工作,您的输入数据必须如下所示:

{
    "inputFile": [
        {
            "Column1": "A",
            "Column2": "B",
            ...
        },
        {
            "Column1": "K",
            "Column2": "L",
            ...
        }
    ]
}

在您的情况下,您将每行放在一个单独的数组中,因此更容易加入这些数组,然后将输出写为文本文件:

Get-Content 'path.json' -Raw |
    ConvertFrom-Json |
    Select-Object -Expand inputFile |
    ForEach-Object { $_ -join ',' } |
    Set-Content 'path.csv'

答案 1 :(得分:0)

所以这很复杂,我希望有人回答。但这对我有用。在不更改JSON中的数据的情况下,我不确定还有什么可以告诉您。

$y = ''
$x = '{"inputFile": [["Column1", "Column2", "Column3", "Column4", "Column5", "Column6", "Column7", "Column8", "Column9", "Column10"], ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"], ["K", "L", "M", "N", "O", "P", "Q", "R", "S", "T"]]}'
($x | ConvertFrom-JSON).inputfile | % {$_ | %{$y += ($_ + "`t")}; $y+="`n"}
$y | out-file x.csv

它基本上只是文本操作。我创建它作为制表符分隔,因为它是默认的excel,但您可以将其更改为其他任何内容。