Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    "numbers": [
    

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading