如何用PowerShell过滤JSON文件,排除指定键名以缩减体积?
处理大体积JSON文件的字段过滤问题
问题场景
需要缩减700MB的JSON文件体积,目标是移除以下不必要的字段:hypernyms、pos、categories、alt_of、inflection_templates、hyponyms、meronyms、source、wikipedia、holonyms、proverbs、head_templates、etymology_text、lang_code、hyphenation、forms、synonyms、antonyms。
尝试的代码要么生成空文件,要么报错:
- 第一次代码执行后生成空文件:
$Obj = [System.IO.File]::ReadLines((Convert-Path -LiteralPath namesonly.json)) | ConvertFrom-Json $foo = Select-Object $Obj -ExcludeProperty hypernyms,pos,categories,alt_of,inflection_templates,hyponyms,meronyms,source,wikipedia,holonyms,proverbs,head_templates,etymology_text,lang_code,hyphenation,forms,synonyms,antonyms $foo | ConvertTo-Json -Depth 100 > namesonlycleaned.json
- 修改后代码报错
A positional parameter cannot be found that accepts argument '*':
$Obj = [System.IO.File]::ReadLines((Convert-Path -LiteralPath namesonly.json)) | ConvertFrom-Json $foo = Select-Object $Obj * -ExcludeProperty hypernyms,pos,categories,alt_of,inflection_templates,hyponyms,meronyms,source,wikipedia,holonyms,proverbs,head_templates,etymology_text,lang_code,hyphenation,forms,synonyms,antonyms $foo | ConvertTo-Json -Depth 100 > namesonlycleaned.json
错误原因
- 第一次代码错误:
Select-Object需要通过管道接收输入对象,而非直接将对象作为位置参数传递。直接传$Obj会导致它把整个JSON数组当作单个对象处理,无法正确过滤每个元素的属性,最终生成空文件。 - 第二次代码错误:参数顺序和语法错误,
*应作为-Property参数的取值,且同样不能直接将$Obj作为位置参数传递给Select-Object。
正确代码
# 读取完整JSON内容并转换为对象数组(700MB文件在现代机器上可正常处理) $jsonData = Get-Content -LiteralPath "namesonly.json" -Raw | ConvertFrom-Json # 过滤掉不需要的属性 $filteredData = $jsonData | Select-Object -ExcludeProperty hypernyms,pos,categories,alt_of,inflection_templates,hyponyms,meronyms,source,wikipedia,holonyms,proverbs,head_templates,etymology_text,lang_code,hyphenation,forms,synonyms,antonyms # 输出到新JSON文件,-Depth确保嵌套结构正确序列化 $filteredData | ConvertTo-Json -Depth 100 | Set-Content -LiteralPath "namesonlycleaned.json"
补充说明
如果机器内存不足以一次性处理700MB文件,可使用**流式JSON解析工具jq**降低内存占用(需先安装jq),示例命令:
jq 'del(.[] | .hypernyms, .pos, .categories, .alt_of, .inflection_templates, .hyponyms, .meronyms, .source, .wikipedia, .holonyms, .proverbs, .head_templates, .etymology_text, .lang_code, .hyphenation, .forms, .synonyms, .antonyms)' namesonly.json > namesonlycleaned.json
内容的提问来源于stack exchange,提问作者Ne Mo
相关产品推荐
相关产品推荐

