Asdfg
Asdfg

Reputation: 12203

Bash - Loop through JSON array

This is how my input looks like:

[
    {
        "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"
    }
]

I need to loop through each object inside the array and fetch OutputKey and OutPutValue and use it in another function.

How do i loop through this array and get the desired values?

I am using GitBash on Windows box.

Upvotes: 0

Views: 2033

Answers (1)

Gilles Quénot
Gilles Quénot

Reputation: 184985

1) your JSON is invalid, this is a correct version (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) as far as means JavaScript Object Notation, I use with in a script :

#!/bin/bash

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

Output

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

Note

  • you can use instead of and the print() command instead of console.log() if you prefer
  • you can use too

Upvotes: 2

Related Questions