Home > Enterprise >  i want to add an int into a json array via python, but only if the int is not in the list already
i want to add an int into a json array via python, but only if the int is not in the list already

Time:05-17

Okay so this is basically my 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)

my test.json looks like this:

{
    "numbers": [
        
    ]
}

when i run the code this happens to the json:

{
    "numbers": [
    

i basically want to check if my random number is in this array, if not, then add.

CodePudding user response:

Seems like you mismatched types when converting from a set to a list for your json? I omitted the curly braces and was able to make it work.

for making sure it's not in the list already: item not in list.

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)

CodePudding user response:

You could take the list of numbers from the JSON and convert them into a a Python Set. And then after inserting the random numbers, convert the set back to a list and dump it to the JSON file

  • Related