我想通过 python 将一个 int 添加到 json 数组中,但前提是该 int 不在列表中
i want to add an int into a json array via python, but only if the int is not in the list already
好的,这基本上是我的 script.py:
import json
import random
PATH = r"C:\Users\Carlo\Desktop\Python\L\test\test.json"
def write_json(data, filename=PATH):
with open (filename, "w") as f:
json.dump(data, f, indent=4)
random_number = random.randint(1,1000)
str(random_number)
print(random_number)
with open (PATH) as json_file:
data = json.load(json_file)
temp = data["numbers"]
y = {f"{str(random_number)}"}
temp.append(y)
write_json(data)
我的 test.json 看起来像这样:
{
"numbers": [
]
}
当我 运行 代码发生这种情况时 json:
{
"numbers": [
我基本上是想检查我的随机数是否在这个数组中,如果不在,则添加。
您可以从 JSON 中获取数字列表并将它们转换为 Python Set。然后在插入随机数后,将集合转换回列表并将其转储到 JSON 文件
在为您的 json 从集合转换为列表时,您似乎不匹配类型?我省略了花括号并使其工作。
用于确保它不在列表中:项目不在列表中。
import json
import random
PATH = r"\Users\Carlo\Desktop\Python\L\test\test.json"
def write_json(data, filename=PATH):
with open (filename, "w") as f:
json.dump(data, f, indent=4)
random_number = random.randint(1,1000)
str(random_number)
print(random_number)
with open (PATH) as json_file:
data = json.load(json_file)
temp = data["numbers"]
y = f"{str(random_number)}"
if (y not in temp):
temp.append(y)
write_json(data)
好的,这基本上是我的 script.py:
import json
import random
PATH = r"C:\Users\Carlo\Desktop\Python\L\test\test.json"
def write_json(data, filename=PATH):
with open (filename, "w") as f:
json.dump(data, f, indent=4)
random_number = random.randint(1,1000)
str(random_number)
print(random_number)
with open (PATH) as json_file:
data = json.load(json_file)
temp = data["numbers"]
y = {f"{str(random_number)}"}
temp.append(y)
write_json(data)
我的 test.json 看起来像这样:
{
"numbers": [
]
}
当我 运行 代码发生这种情况时 json:
{
"numbers": [
我基本上是想检查我的随机数是否在这个数组中,如果不在,则添加。
您可以从 JSON 中获取数字列表并将它们转换为 Python Set。然后在插入随机数后,将集合转换回列表并将其转储到 JSON 文件
在为您的 json 从集合转换为列表时,您似乎不匹配类型?我省略了花括号并使其工作。
用于确保它不在列表中:项目不在列表中。
import json
import random
PATH = r"\Users\Carlo\Desktop\Python\L\test\test.json"
def write_json(data, filename=PATH):
with open (filename, "w") as f:
json.dump(data, f, indent=4)
random_number = random.randint(1,1000)
str(random_number)
print(random_number)
with open (PATH) as json_file:
data = json.load(json_file)
temp = data["numbers"]
y = f"{str(random_number)}"
if (y not in temp):
temp.append(y)
write_json(data)