Skip to content Skip to sidebar Skip to footer

How To Build Json From Python Script?

I am new to JSON and I want to generate a JSON file from a python script For example: #take input from the user num = int(input('Enter a number: ')) # prime numbers are greater t

Solution 1:

There is a json library that comes with python, here's the docs

import json
#take input from the user

num = int(input("Enter a number: "))

# prime numbers are greater than 1if num > 1:

#check for factors
prime_numbers = []
not_prime = []
for i inrange(2,num):
    if (num % i) == 0:
        print(num,"is not a prime number")
        print(i,"times",num//i,"is",num)
        not_prime.append(num)
        breakelse:
        prime_numbers.append(num)
        print(num,"is a prime number")


fh = open("my_json.json", "a+")
fh.write(json.dumps({"prime": prime_numbers, "not_prime": not_prime})) # added an extra ')'.. code will now work
fh.close()

json is nice :)

Solution 2:

Here's an example of using the json module with a dictionary

import json
# make sample dict with comprehension
dict1 = {k: v for (k, v) inenumerate(range(10))}
json1 = json.dumps(dict1)

Which has the following value

'{"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9}'

So, create a dict, use the module.

Post a Comment for "How To Build Json From Python Script?"