You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell将单行JSON格式化为结构化多行JSON?

解决PowerShell中JSON单行转结构化多行的问题

当然可以!PowerShell本身就自带了非常方便的JSON格式化能力,完全不需要额外安装工具,下面给你几种实用的方法:

方法一:写入文件时直接格式化(推荐)

如果你的JSON一开始是字符串形式的变量,先把它解析成PowerShell对象,再转换回带缩进的结构化JSON并保存:

# 你的原始单行JSON字符串变量
$rawJsonString = '{ "persistentdataapi": "https://somevalue.azurewebsites.net/", "collectioncountapi": "https://anothervalue.azurewebsites.net/", "eventserviceapi": "https://thirdvalue.azurewebsites.net/", "securityserviceapi": "https://fourthvalue.azurewebsites.net/" }'

# 1. 解析JSON字符串为PowerShell对象
$parsedJson = $rawJsonString | ConvertFrom-Json

# 2. 转换回格式化的JSON并保存到文件
# -Depth 参数要设置足够大,避免嵌套层级深的JSON被截断(默认是2)
$parsedJson | ConvertTo-Json -Depth 10 | Out-File -Path "formatted-config.json" -Encoding utf8

方法二:格式化已存在的单行JSON文件

如果已经有一个保存好的单行JSON文件,直接读取并格式化:

# 读取单行JSON文件,解析后重新格式化输出
Get-Content -Path "unformatted.json" -Raw | ConvertFrom-Json | ConvertTo-Json -Depth 10 | Out-File -Path "formatted.json" -Encoding utf8

这里的-Raw参数很重要,它会把整个文件内容读取为单个字符串,避免ConvertFrom-Json因为换行符问题解析失败。

方法三:直接从PowerShell对象生成格式化JSON

如果你的JSON数据是直接在PowerShell中构建的对象(不是字符串),可以直接一步生成结构化JSON:

# 构建配置对象
$config = [PSCustomObject]@{
    persistentdataapi = "https://somevalue.azurewebsites.net/"
    collectioncountapi = "https://anothervalue.azurewebsites.net/"
    eventserviceapi = "https://thirdvalue.azurewebsites.net/"
    securityserviceapi = "https://fourthvalue.azurewebsites.net/"
}

# 直接保存为格式化的JSON
$config | ConvertTo-Json -Depth 10 | Set-Content -Path "config.json" -Encoding utf8

关键说明

ConvertTo-Json cmdlet 默认就会输出带缩进的多行结构化格式,核心是要先把原始的单行JSON字符串解析成PowerShell对象(通过ConvertFrom-Json),再转换回JSON字符串,这样就能得到易读的格式了。

内容的提问来源于stack exchange,提问作者Vasyl Stepulo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:16:41