我正在尝试在启动解析脚本之前将文件验证为JSON投诉。我试图捕获重复键或文件是无效的JSOn文件。但它似乎没有用,任何帮助请:
function ParseFile([string]$file, [int]$domainNumber)
{
# read entire JSON file and parse
$bytes = [system.io.file]::ReadAllText($file)
$json = ConvertFrom-Json $bytes
$text = Get-Content $file -Raw
try {
$powershellRepresentation = ConvertFrom-Json $text -ErrorAction Stop;
$validJson = $true;
Write-Error "IN TRY";
} catch {
Write-Error "IN CATCH";
$validJson = $false;
}
if ($validJson) {
Write-Error "Provided text has been correctly parsed to JSON";
Exit 1
} else {
Write-Error "Provided text is not a JSON valid string";
Exit 1
}
它总是说文件是有效的JSON,即使文件包含重复的密钥。 CALL powershell.exe -noprofile -executionpolicy bypass -file D:\ Tools \ Scripts json_files \ config.pkg.xml ParseFile:111在D:\ Tools \ Scripts \ json.ps1:110 char:4 + ParseFile $ file $ domainNumber + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo:NotSpecified :( :) [Write-Error],WriteErrorException + FullyQualifiedErrorId:Microsoft.PowerShell .Commands.WriteErrorException,ParseFile
ParseFile:2222在D:\ Tools \ Scripts \ json.ps1:110 char:4 + ParseFile $ file $ domainNumber + ~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~ + CategoryInfo:NotSpecified:(:) [Write-Error],WriteErrorException + FullyQualifiedErrorId:Microsoft.PowerShell.Commands.WriteErrorException,ParseFile
ParseFile:提供的文本已正确解析为JSON在D:\ Tools \ Scripts \ json.ps1:110 char:4 + ParseFile $ file $ domainNumber + ~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ + CategoryInfo:NotSpecified :( :) [Write-Error],WriteErrorException + FullyQualifiedErrorId:Microsoft.PowerShell.Commands.WriteErrorException,ParseFile
How to check if file has valid JSON syntax in Powershell
示例:
{
"sr_version": {
"major": 1,
"minor": 1,
"patch": 1
},
"sr_domain": {
"soc": "msm",
"domain": "Audio",
"subdomain": "root",
"qmi_instance_id": 74
},
"sr_domain": {
"soc": "msm",
"domain": "Audio",
"subdomain": "root",
"qmi_instance_id": 74
},
"sr_service": [{
"provider": "tms",
"service": "servreg",
"service_data_valid": 0,
"service_data": 0
}]
}
答案 0 :(得分:1)
根据Does JSON syntax allow duplicate keys in an object?回答:两次同一级别的同一个键不一定是错误。
.NET反序列化程序(" System.Web.Script.Serialization.JavaScriptSerializer"?)不会将其检测为错误,只保留第二个值。
如果您尝试使用相同的密钥,但区分大小写,则会出现错误。
ConvertFrom-Json : Cannot convert the JSON string because a dictionary that was converted from the string contains the duplicated keys 'Key' and 'key'.
At C:\Temp\Untitled8.ps1:27 char:11
+ $b = $a | ConvertFrom-Json
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [ConvertFrom-Json], InvalidOperationException
+ FullyQualifiedErrorId : DuplicateKeysInJsonString,Microsoft.PowerShell.Commands.ConvertFromJsonCommand