0

I'm currently trying to parse a given json file:

{
  "Level1": [
    {
      "Level2": [
        {
          "Level3-1": "ValueOfLevel3-1",
          "Level3-2": [
            {
              "Value": "Value-01",
              "Key": "Key01"
            },
            {
              "Value": "Value-02",
              "Key": "Key02"
            }
          ]
        }
      ]
    },
    {
      "Level2": [
        {
          "Level3-1": "ValueOfLevel3-1",
          "Level3-2": [
            {
              "Value": "Value-04",
              "Key": "Key02"
            },
            {
              "Value": "Value-03",
              "Key": "Key01"
            }
          ]
        }
      ]
    }
  ]
}

We're working on bash (any tool like python is available) and need to parse the json file to execute actions on each occurance of "topid".

So for example just pasting out the values of "id" and "key" via "echo" the resulting commands should be:

echo "ValueOfLevel3-1" >> /tmp/file
echo "Value-02" >> /tmp/file
echo "ValueOfLevel3-1" >> /tmp/file
echo "Value-04" >> /tmp/file

While the problem is, that it should search for the right keyname - in this case keyname2

Is something like that possible?

Cheers, Matthias

1 Answers1

0

Searching a little bit I found: Parsing json and searching through it

The solution - given that the json is contained in test.txt is:

import json
import sys
from pprint import pprint

with open('test.txt') as data_file:
    data = json.load(data_file)

    for c in data['Level1']:
            for d in c.get('Level2'):
                for f in d.get('Level3-2'):
                    if 'Key02' in f.get('Key'):
                        print d.get('Level3-1'), "\t", f.get('Value')



$ python runme2.py
ValueOfLevel3-1         Value-02
ValueOfLevel3-1         Value-04
Community
  • 1
  • 1