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

PowerShell中JSON转哈希表时是否会截断值?

问题解答

这个截断现象并非JSON转哈希表操作导致的,核心原因是PowerShell的默认输出格式化规则,而非哈希表本身对值的长度有限制。

具体原因

PowerShell在输出哈希表对象时,会默认采用表格视图展示。为了保持表格的可读性,它会自动截断过长的字符串(默认截断长度约166字符),并用省略号结尾。但实际上,哈希表中存储的synopsis值是完整的,只是显示/输出时被格式化截断了。

验证方式

你可以直接访问哈希表的对应键值,查看完整内容:

$jFile = "C:\psfiles\json\json_example.json"
$json = (Get-Content $jFile -Raw) | ConvertFrom-Json
$hashTable = $json.books | ConvertTo-HashTable
# 直接输出synopsis的完整内容到文件
$hashTable.synopsis | Out-File "full_synopsis.txt" -Force

打开full_synopsis.txt就能看到完整的图书简介,证明哈希表并未截断数据。

解决办法

如果需要完整输出哈希表的所有内容,避免截断,可以采用以下两种方式:

方式一:转成JSON格式输出

利用ConvertTo-Json将哈希表转回JSON格式,再输出到文件,能完整保留所有内容:

$jFile = "C:\psfiles\json\json_example.json"
$File = "C:\psfiles\output.txt"
$json = (Get-Content $jFile -Raw) | ConvertFrom-Json
$json.books | ConvertTo-HashTable | ConvertTo-Json -Depth 10 | Out-File -FilePath $File -Force

方式二:自定义遍历输出

手动遍历哈希表的键值对,逐行输出,确保字符串不被截断:

$jFile = "C:\psfiles\json\json_example.json"
$File = "C:\psfiles\output.txt"
$json = (Get-Content $jFile -Raw) | ConvertFrom-Json
$hashTable = $json.books | ConvertTo-HashTable

# 生成完整的键值对文本
$outputLines = $hashTable.GetEnumerator() | ForEach-Object {
    "$($_.Key): $($_.Value)"
}

$outputLines | Out-File -FilePath $File -Force

补充说明

PowerShell 5.1的哈希表本身不存在键或值的长度限制——数据截断只发生在输出展示环节,和哈希表的存储机制无关。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:43:11