Bash - 循环通过JSON数组

时间:2016-09-27 20:50:42

标签: windows bash

这是我输入的样子:

[
    {
        "Description": "Description 1"
        "OutputKey": "OutputKey 1"
        "OutputValue": "OutputValue 1"
    }
    {
        "Description": "Description 2"
        "OutputKey": "OutputKey 2"
        "OutputValue": "OutputValue 2"
    }
    {
        "Description": "Description 3"
        "OutputKey": "OutputKey 3"
        "OutputValue": "OutputValue 3"
    }
    {
        "Description": "Description 4"
        "OutputKey": "OutputKey 4"
        "OutputValue": "OutputValue 4"
    }
    {
        "Description": "Description 5"
        "OutputKey": "OutputKey 5"
        "OutputValue": "OutputValue "
    }
    {
        "Description": "Description 6"
        "OutputKey": "OutputKey 6"
        "OutputValue": "OutputValue 6"
    }
]

我需要遍历数组中的每个对象并获取OutputKey和OutPutValue并在另一个函数中使用它。

如何遍历此数组并获得所需的值?

我在Windows上使用GitBash。

1 个答案:

答案 0 :(得分:1)

1)您的JSON无效,这是正确的版本(input.json):

[
    {
        "Description": "Description 1",
        "OutputKey": "OutputKey 1",
        "OutputValue": "OutputValue 1"
    },
    {
        "Description": "Description 2",
        "OutputKey": "OutputKey 2",
        "OutputValue": "OutputValue 2"
    },
    {
        "Description": "Description 3",
        "OutputKey": "OutputKey 3",
        "OutputValue": "OutputValue 3"
    },
    {
        "Description": "Description 4",
        "OutputKey": "OutputKey 4",
        "OutputValue": "OutputValue 4"
    },
    {
        "Description": "Description 5",
        "OutputKey": "OutputKey 5",
        "OutputValue": "OutputValue "
    },
    {
        "Description": "Description 6",
        "OutputKey": "OutputKey 6",
        "OutputValue": "OutputValue 6"
    }
]

2)至于表示 JavaScript Object Notation ,我在脚本中使用

#!/bin/bash

node<<EOF
var arr = $(cat input.json);
arr.forEach(function(el){ console.log(el.OutputKey + " " + el.OutputValue ); })
EOF

输出

OutputKey 1 OutputValue 1
OutputKey 2 OutputValue 2
OutputKey 3 OutputValue 3
OutputKey 4 OutputValue 4
OutputKey 5 OutputValue 
OutputKey 6 OutputValue 6

注意

  • 如果您愿意,可以使用代替print()命令代替console.log()
  • 您也可以使用