首页 > 解决方案 > 通过“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,值:man4id

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 文件...

标签: jsonpowershell

解决方案


您的 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"

推荐阅读