You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python提取JSON文件内容并将IP地址保存到新JSON文件

Python提取JSON中的IP地址并保存到新JSON文件

核心实现思路

利用Python内置的json模块完成JSON文件的读写操作,遍历原始JSON数组中的每个对象,提取ip字段的值,最后将收集到的IP列表写入新的JSON文件。

完整代码示例(读取本地JSON文件)

import json

# 读取原始JSON文件
with open('input.json', 'r', encoding='utf-8') as input_file:
    original_data = json.load(input_file)

# 提取所有有效IP地址(自动过滤缺失ip字段的条目)
ip_addresses = [entry['ip'] for entry in original_data if 'ip' in entry]

# 将IP列表写入新JSON文件
with open('extracted_ips.json', 'w', encoding='utf-8') as output_file:
    json.dump(ip_addresses, output_file, indent=4, ensure_ascii=False)

代码说明

  1. 读取JSON文件:json.load()将本地JSON文件解析为Python列表对象,每个列表元素是包含IP信息的字典。
  2. 提取IP地址:使用列表推导式遍历所有条目,仅保留包含ip字段的条目对应的IP值,避免因缺失字段引发KeyError。
  3. 保存结果:json.dump()将IP列表转为格式化的JSON字符串写入文件,indent=4让输出更易读,ensure_ascii=False确保兼容特殊字符(如果有的话)。

直接处理JSON字符串的场景

如果你的JSON数据是以字符串形式存在(而非本地文件),可以用以下代码:

import json

# 示例JSON字符串(注意替换xxx为实际端口数字,否则解析会报错)
sample_json = '''
[
    {   "ip": "192.168.0.135",   "timestamp": "1662977246", "ports": [ {"port": 80, "proto": "tcp", "status": "open", "reason": "syn-ack", "ttl": 64} ] },
    {   "ip": "192.168.0.136",   "timestamp": "1662977246", "ports": [ {"port": 443, "proto": "tcp", "status": "open", "reason": "syn-ack", "ttl": 64} ] }
]
'''

# 解析JSON字符串
data = json.loads(sample_json)

# 提取IP
ip_list = [item['ip'] for item in data if 'ip' in item]

# 保存到文件
with open('extracted_ips.json', 'w', encoding='utf-8') as f:
    json.dump(ip_list, f, indent=4)

注意事项

  • 确保原始JSON格式合法:示例中的xxx需要替换为实际数字,否则json.load()会抛出解析错误。
  • 如果原始JSON结构不是数组(比如是嵌套字典),需要调整遍历逻辑以匹配实际数据结构。

内容的提问来源于stack exchange,提问作者Kuba Kaktus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 17:50:23