Python3 json 仅当其他字段大于值时才将值逐行输出到文件
Python3 json output values to file line by line only if other fields are greater than value
我已经在 python3 中使用 urllib.request 检索了远程 json 并且想逐行转储 IP 地址的值(即 ip:127.0.0.1 将是 127.0.0.1,下一行是下一个 IP)如果它符合某些条件。其他关键值包括分数(每个类别一个整数值)和类别(一个或多个可能的字符串值)。
我想检查分数是否高于(比如 10),并且类别编号是否等于一个或多个值的列表。如果它符合参数,我只需要将这些 IP 地址逐行添加到文本文件中。
这是我检索 json 的方法:
ip_fetch = urllib.request.urlopen('https://testonly.com/ip.json').read().decode('utf8')
我已经加载了 json 模块,但不知道从这里去哪里。
我正在处理的 json 数据示例,不止一类:
"127.0.0.1" : {
"Test" : "10",
"Prod" : "20"
},
我写了一个简单的示例,应该向您展示如何遍历 json 对象以及如何写入文件:
import json
j = json.loads(test)
threshold = 10
validCategories = ["Test"]
f=open("test.txt",'w')
for ip, categories in j.items():
addToList = False
for category, rank in categories.items():
if category in validCategories and int(rank) >= threshold:
addToList = True
if addToList:
f.write("{}\n".format(ip))
f.close()
希望对您有所帮助。为了进行测试,我使用了以下 json-string:
test = """
{
"127.0.0.1" : {
"Test" : "10",
"Prod" : "20"
},
"127.0.0.2" : {
"Test" : "5",
"Prod" : "20"
},
"127.0.0.3" : {
"Test" : "5",
"Prod" : "5",
"Test2": "20"
}
}
"""
我已经在 python3 中使用 urllib.request 检索了远程 json 并且想逐行转储 IP 地址的值(即 ip:127.0.0.1 将是 127.0.0.1,下一行是下一个 IP)如果它符合某些条件。其他关键值包括分数(每个类别一个整数值)和类别(一个或多个可能的字符串值)。
我想检查分数是否高于(比如 10),并且类别编号是否等于一个或多个值的列表。如果它符合参数,我只需要将这些 IP 地址逐行添加到文本文件中。
这是我检索 json 的方法:
ip_fetch = urllib.request.urlopen('https://testonly.com/ip.json').read().decode('utf8')
我已经加载了 json 模块,但不知道从这里去哪里。
我正在处理的 json 数据示例,不止一类:
"127.0.0.1" : {
"Test" : "10",
"Prod" : "20"
},
我写了一个简单的示例,应该向您展示如何遍历 json 对象以及如何写入文件:
import json
j = json.loads(test)
threshold = 10
validCategories = ["Test"]
f=open("test.txt",'w')
for ip, categories in j.items():
addToList = False
for category, rank in categories.items():
if category in validCategories and int(rank) >= threshold:
addToList = True
if addToList:
f.write("{}\n".format(ip))
f.close()
希望对您有所帮助。为了进行测试,我使用了以下 json-string:
test = """
{
"127.0.0.1" : {
"Test" : "10",
"Prod" : "20"
},
"127.0.0.2" : {
"Test" : "5",
"Prod" : "20"
},
"127.0.0.3" : {
"Test" : "5",
"Prod" : "5",
"Test2": "20"
}
}
"""