json - 通过“powershell”命令从 json 文件中提取数据
问题描述
我正在尝试从我的json
文件中获取数据,但我的代码仍然无法正常工作。你有什么建议吗?
JSON文件:
"nodes": [
{
"id": "elfe",
"apps": [
{
"id": "man1",
"age" = "5"
"power" ="strenght"
},
{
"id": "man2",
"age" = "10"
"power" ="strenght"
}],
"id": "monster",
"apps": [
{
"id": "man3",
"age" = "5"
"power" ="strenght"
},
{
"id": "man4",
"age" = "10"
"power" ="strenght"
}],
还有,我在 PowerShell 中的代码。我只想在我的文件中为每个精灵和怪物获取man1
, man2
, man3
,值:man4
id
man1
man2
在一个文件和另一个文件中:
man3
man4
我的批处理脚本:
Powershell -Nop -C "(Get-Content .\config.json |ConvertFrom-Json).Nodes | Select-Object -ExpandProperty id | Where-Object id -eq elfe" >> file.txt
编辑:我无法修改我的 JSON 文件...
解决方案
您的 json 无效,以下是带有数据提取的更正版本:
$json = @"
{
"nodes":[
{
"id":"elfe",
"apps":[
{
"id":"man1",
"age":5,
"power":"strenght"
},
{
"id":"man2",
"age":10,
"power":"strenght"
}]},
{ "id":"monster",
"apps":[
{
"id":"man3",
"age" :"5",
"power":"strenght"
},
{
"id":"man4",
"age":"10",
"power":"strenght"
}]}
]}
"@
$data = $json | ConvertFrom-Json
$data.nodes | where {$_.id -eq "elfe"} | foreach {$_.apps.id >> "elfe.txt"}
但是您可能只是在引用该命令时遇到了麻烦。下面是一个工作版本。我用 tee 替换了 >> - 它会覆盖输出文件并在屏幕上打印结果。
powershell -nop -c "(cat test.json | ConvertFrom-Json).nodes | where {$_.id -eq 'elfe'} | foreach {$_.apps.id} | tee out.txt"
推荐阅读
- javascript - 如何在 data.forEach 函数中使用临时变量而不是绝对列值
- linux - AWS 会话管理器欢迎消息
- firebase - 我们可以自动删除firestore中文档的属性吗?
- c++ - 旋转数组时出现 SIGABRT 错误
- avplayer - 将 AVPlayer 音频输出路由到 AVAudioEngine
- python - 如何连接两个字符串并在 CSV 中添加名称 python
- vue.js - Vue.js 路由器链接未更新
- sql-server - 如何提高 SQL 数据库的多重 JOIN 性能
- visual-studio - 如何在 Linux 上设置 vs 项目的 PostBuildEvent 以从 FTP 下载?
- amazon-web-services - 无法将 Amazon lex 集成到我的网站中