0

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 than 1

if num > 1:

#check for factors

for i in range(2,num):
    if (num % i) == 0:
        print(num,"is not a prime number")
        print(i,"times",num//i,"is",num)
        break
else:
    print(num,"is a prime number")

# if the input number is less than or equal to 1, it is not prime

else: print(num,"is not a prime number")

For the above python script, how to generate a JSON file? Is there any tool or a software?

I don't want to create a JSON file manually. The above code is just an example.

I have a code for object detection and multiple input images. In each image the objects are same, but the location of the objects are different.

inputImage: Trolley_Problem

tramTemplate: tram1

UPDATE 1:

import numpy as np
import cv2

# Read the main image

inputImage = cv2.imread("Trolley_Problem.jpg")

# Convert it to grayscale

inputImageGray = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)

# Read the templates

tramTemplate = cv2.imread("tram1.jpg")

# Convert the templates to grayscale

tramTemplateGray = cv2.cvtColor(tramTemplate, cv2.COLOR_BGR2GRAY)

#Store width and height of the templates in w and h

h1,w1 = tramTemplateGray.shape

# Perform match operations.

tramResult = cv2.matchTemplate(inputImageGray,tramTemplateGray, cv2.TM_CCOEFF_NORMED)

# Specify a threshold

threshold = 0.75

# Store the coordinates of matched area in a numpy array

loc1 = np.where( tramResult >= threshold)

for pt in zip(*loc1[::-1]):
    cv2.rectangle(inputImage,pt, (pt[0] + w1, pt[1] + h1), (0,255,255), 1)
    cv2.putText(inputImage,"Tram Detected", (200,50), font, 0.5, 255)

# Show the final result

cv2.imwrite(r "Trolley_Problem_Result.jpg", inputImage)`

So, I have to generate JSON file for this object detection program.

Thank you

4
  • docs.python.org/2/library/json.html Commented Mar 23, 2018 at 18:32
  • I'm sorry, what? What does "generate a JSON file from a python script" mean? Why does the second half of the question suddenly start talking about images and object detection? I have no idea what's going on in this question. Commented Mar 23, 2018 at 18:33
  • there is no relation of code you present with json... will you please update your question so that we can understand what exactly you want to do? post some of your trial code. Commented Mar 23, 2018 at 18:36
  • @py-D I have mentioned that the code given is just an example. in general, I want to write the python output in json file/ json format. I have updated the question. Please have a look. Thank you very much :) Commented Mar 23, 2018 at 22:55

2 Answers 2

5

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 1

if num > 1:

#check for factors
prime_numbers = []
not_prime = []
for i in range(2,num):
    if (num % i) == 0:
        print(num,"is not a prime number")
        print(i,"times",num//i,"is",num)
        not_prime.append(num)
        break
    else:
        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 :)

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you :) I guess, this is what I want. But when I run your code, I am getting the following error: "File "<ipython-input-11-7895411c808b>", line 25 fh.close() ^ SyntaxError: invalid syntax" Do you have any idea why?
Not off the top of my head, that's strange. As long as fh refers to an open file object fh.close() should work docs.python.org/3.5/tutorial/…
Thank you very much. At least now I know where to start from! It was a great help!
0

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) in enumerate(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.

2 Comments

Hi Aaron, I think what you are doing is JSON to Python, but I want python to JSON i.e I have a python script and I want to convert it into JSON. Do you know how can I do that? Thank you :)
I'm not doing JSON to python. I'm taking example python data (an enumerated list converted to a dict) and putting it into JSON format. If you need this in an actual text file, you should look at the python I/O documentation that can be found here: docs.python.org/3/tutorial/inputoutput.html It has great examples of writing to files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.