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

PowerShell脚本处理JSON文件遇MaxJsonLength超限错误求解决方案

解决PowerShell中ConvertTo-Json的maxJsonLength超限问题

方案1:使用Newtonsoft.Json第三方库(推荐)

PowerShell自带的ConvertTo-Json基于.NET的JavaScriptSerializer,存在默认长度限制。使用Newtonsoft.Json可以避开这个限制,同时支持更灵活的JSON处理:

# 以当前用户权限安装模块(首次运行需要管理员权限)
Install-Module -Name Newtonsoft.Json -Scope CurrentUser -Force

# 导入模块
Import-Module Newtonsoft.Json

# 下载并解析JSON数据
$url = "https://someURL/file.json"
$json = (New-Object System.Net.WebClient).DownloadString($url)
$data = $json | ConvertFrom-Json

# 序列化并保存,无长度限制且支持格式化输出
[Newtonsoft.Json.JsonConvert]::SerializeObject($data, [Newtonsoft.Json.Formatting]::Indented) | Out-File "C:\scripts\LW\data.json" -Encoding UTF8

方案2:修改.NET底层序列化器的长度限制

如果不想安装第三方模块,可以通过反射修改JavaScriptSerializer的_maxJsonLength属性,解除长度限制:

$url = "https://someURL/file.json"
$json = (New-Object System.Net.WebClient).DownloadString($url)
$data = $json | ConvertFrom-Json

# 获取JavaScriptSerializer类型并修改最大长度
$jsSerializerType = [Type]::GetType("System.Web.Script.Serialization.JavaScriptSerializer, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
$maxLengthField = $jsSerializerType.GetField("_maxJsonLength", [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Instance)
$serializer = New-Object $jsSerializerType
$maxLengthField.SetValue($serializer, [int]::MaxValue)

# 序列化并保存结果
$serializer.Serialize($data) | Out-File "C:\scripts\LW\data.json" -Encoding UTF8

方案3:升级到PowerShell 7+

PowerShell 7及以上版本对ConvertTo-Json做了优化,大幅提升了默认的JSON长度限制,大部分场景下无需额外配置即可处理大文件。如果你的环境允许升级,直接替换原有代码即可:

$url = "https://someURL/file.json"
$json = Invoke-RestMethod -Uri $url
$json | ConvertTo-Json -Depth 100 | Out-File "C:\scripts\LW\data.json" -Encoding UTF8

注:PowerShell 7推荐使用Invoke-RestMethod代替WebClient,它会自动解析JSON,代码更简洁。

内容的提问来源于stack exchange,提问作者Jose A.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 19:17:15