如何过滤json数据

时间:2017-01-10 13:04:25

标签: json python-2.7

我只需要保存PublicIpAddress和PrivateIpAddress等少数字段,同时省略大型json文件中的所有其他字段。我怎么能用Python做到这一点,本机就有“jq”这样的功能。提前谢谢。

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

编辑:我需要在python脚本中执行此操作,而不是在python环境之外。

1 个答案:

答案 0 :(得分:1)

试试这个 -

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'])