从 JSON 日志中返回与从 CSV 读取时匹配某些内容的行?

问题描述 投票:0回答:1

因此,在我的 CSV 文件中使用带有 Python 的脚本,我想查看 IP 和时间戳值是否以某种方式存在于 JSON 日志文件的行条目中,如果存在,则将该特定 JSON 日志条目返回到另一个文件。我试图使其通用,以便它适用于所有 IP 地址。示例 CSV 文件如下所示;

"clientip",""destip","dest_hostname","timestamp"
 "127.0.0.1","0.0.0.0","randomhost","2023-09-09T04:18:22.542Z"

Json 日志文件中的示例行条目

{"log": "09-Sept-2023 rate-limit: info: client @xyz 127.0.0.1, "stream":"stderr", "time": 2023-09-09T04:18:22.542Z"}

当存在匹配时,我们希望在 output.txt 文件中返回 JSON 日志文件中的行。 JSON 文件没有像 CSV 那样的相同字段和组织(带有 clientip、destip、dest_hostname、timestamp),但我希望我仍然可以至少将 JSON 日志文件中的行返回到具有匹配项的新文件在 clientip 上(就像我们在“info: client @xyz 127.0.0.1”中看到的 127.0.0.1),也许还有时间戳。

我之前尝试过 shell,但找不到任何匹配项。我尝试了连接命令

join file.csv xyz-json.log > output.txt
但它没有产生任何结果,
awk
也没有产生任何像“NR==FR”这样的规范。

这就是为什么我现在尝试用 Python 来完成这个工作。我也是 Python 新手,但这就是我的大致想法,暂时忽略缩进。

import csv
for line in csv
for line in json-logs
if csv == json-logs
print l1 == l2

我将不胜感激任何帮助/协助!

python json python-3.x opencsv read-csv
1个回答
0
投票

一种可能是将 csv 和 json 文件读入数据帧;从 json

ip
中提取任何
log
值,然后从
ip
time
上的 json 文件进行内部合并,并输出合并后剩余的行:

dfc = pd.read_csv('test.csv')
dfj = pd.read_json('test.jsonl', lines=True)
dfj['ip'] = dfj['log'].str.extract(r'(\d+(?:\.\d+){3})')
res = dfj.merge(dfc, left_on=['ip', 'time'], right_on=['clientip','timestamp'],how='inner')
res[['log', 'stream', 'time']].to_json('result.jsonl', orient='records', lines=True)
© www.soinside.com 2019 - 2024. All rights reserved.