Issa Daniel
Issa Daniel

Reputation: 11

Filtering out desired data from a JSON file (Python)

this is a sample of my json file:

{
"pops": [{
        "name": "pop_a",
        "subnets": {
            "Public": ["1.1.1.0/24,2.2.2.0/24"],
            "Private": ["192.168.0.0/24,192.168.1.0/24"],
        "more DATA":""  
        }
    },
    {
        "name": "pop_b",
        "subnets": {
            "Public": ["3.3.3.0/24,4.4.4.0/24"],
            "Private": ["192.168.2.0/24,192.168.3.0/24"],
        "more DATA":""
        }
    }
]
}

after i read it, i want to make a dic object and store some of the things that i need from this file. i want my object to be like this ..

[{
    "name": "pop_a",
    "subnets": {"Public": ["1.1.1.0/24,2.2.2.0/24"],"Private": ["192.168.0.0/24,192.168.1.0/24"]}
},
{
    "name": "pop_b",
    "subnets": {"Public": ["3.3.3.0/24,4.4.4.0/24"],"Private": ["192.168.2.0/24,192.168.3.0/24"]}
}]

then i want to be able to access some of the public/private values

here is what i tried, and i know there is update(), setdefault() that gave also same unwanted results

def my_funckion():
   nt_json = [{'name':"",'subnets':[]}]
   Pname = []
   Psubnet= []

   for pop in pop_json['pops']:  # it print only the last key/value
      nt_json[0]['name']= pop['name']
      nt_json[0]['subnet'] = pop['subnet']
   pprint (nt_json)

  for pop in pop_json['pops']: 
   """
     it print the names in a row then all of the ipss
   """
     Pname.append(pop['name'])
     Pgre.append(pop['subnet'])
     nt_json['pop_name'] = Pname
     nt_json['subnet']= Psubnet
   pprint (nt_json)

Upvotes: 0

Views: 742

Answers (1)

cs95
cs95

Reputation: 402922

Here's a quick solution using list comprehension. Note that this approach can be taken only with enough knowledge of the json structure.

>>> import json
>>>
>>> data = ... # your data
>>> new_data = [{ "name" : x["name"], "subnets" : {"Public" : x["subnets"]["Public"], "Private" : x["subnets"]["Private"]}} for x in data["pops"]]
>>>
>>> print(json.dumps(new_data, indent=2))
[
  {
    "name": "pop_a",
    "subnets": {
      "Private": [
        "192.168.0.0/24,192.168.1.0/24"
      ],
      "Public": [
        "1.1.1.0/24,2.2.2.0/24"
      ]
    }
  },
  {
    "name": "pop_b",
    "subnets": {
      "Private": [
        "192.168.2.0/24,192.168.3.0/24"
      ],
      "Public": [
        "3.3.3.0/24,4.4.4.0/24"
      ]
    }
  }
]

Upvotes: 1

Related Questions