从json文件通过“ powershell”命令提取数据

时间:2018-11-25 00:42:04

标签: json powershell

我正在尝试从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精灵和类似的怪兽获得man2man3man4id值:

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

1 个答案:

答案 0 :(得分:0)

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