PowerShell处理JSON转Hashtable遇重复键错误,求问题分析
问题分析与修正方案
错误原因
- 遍历逻辑完全错误:原代码遍历的是
$b.solutionName.GetEnumerator(),但$b是JSON转换后的对象数组,$b.solutionName会返回数组中所有对象的solutionName属性组成的集合,遍历这个集合的枚举器根本无法获取单个solution对象,完全偏离了需求。 - 属性取值错误:循环内
$name = $b.solutionName.toString()和$shortcode = $b.solutionShortcode.toString()都是取整个数组的属性集合,转换为字符串后得到的是System.Object[],这就导致每次循环都在尝试往Hashtable里添加同一个键System.Object[],自然触发“Key already added”错误,最终只能得到一个无效的键值对。
修正后的PowerShell代码
$buildDictionary = @{} # 读取JSON文件并转换为对象数组 $solutions = Get-Content -Raw -Path ./temp.json | ConvertFrom-Json # 遍历每个solution对象 foreach ($solution in $solutions) { $name = $solution.solutionName $shortcode = $solution.solutionShortcode # 处理空短码的情况 if ([string]::IsNullOrEmpty($shortcode)) { $shortcode = "0xxx" } # 往Hashtable添加键值对(键存在时会直接覆盖,如需避免可先判断ContainsKey) $buildDictionary[$name] = $shortcode } # 输出最终的Hashtable Write-Output $buildDictionary
修正说明
- 直接遍历转换后的对象数组
$solutions,每次迭代获取单个solution对象,确保处理的是独立的条目。 - 从当前迭代的
$solution对象中提取对应的属性值,保证每个键值对都是单个solution的有效数据。 - 使用
$buildDictionary[$name] = $shortcode的方式添加数据,比Add()方法更灵活,键存在时会自动覆盖(若需要严格避免覆盖,可先通过$buildDictionary.ContainsKey($name)判断)。
内容的提问来源于stack exchange,提问作者Dan Styles
相关产品推荐
相关产品推荐

