user1619524
user1619524

Reputation: 1624

How to filter json data

I just need to save few fields like PublicIpAddress and PrivateIpAddress while omitting everything else in a large json file. How can I do this in Python, is there "jq" like functionality natively. Thank you in advance.

[
      {
        "EbsOptimized": false,
        "LaunchTime": "2017-01-10T12:19:30+00:00", 
        "PublicIpAddress": "54.229.28.216",
        "PrivateIpAddress": "172.31.2.152"
      },
      {
        "EbsOptimized": false,
        "LaunchTime": "2017-01-10T12:19:30+00:00",
        "PublicIpAddress": "54.229.28.217",
        "PrivateIpAddress": "172.31.2.153"
      }
    ]

Edit: I need to do this in a python script, not outside of python environment.

Upvotes: 1

Views: 1013

Answers (1)

Vidyadhar Mandke
Vidyadhar Mandke

Reputation: 588

Try this -

import json
json_data = '[
          {
            "EbsOptimized": false,
            "LaunchTime": "2017-01-10T12:19:30+00:00", 
            "PublicIpAddress": "54.229.28.216",
            "PrivateIpAddress": "172.31.2.152"
          },
          {
            "EbsOptimized": false,
            "LaunchTime": "2017-01-10T12:19:30+00:00",
            "PublicIpAddress": "54.229.28.217",
            "PrivateIpAddress": "172.31.2.153"
          }
        ]'
dict = json.loads(json_data)
for data in dict:
    print(data['PublicIpAddress'])

Upvotes: 1

Related Questions