0

I'm trying to generate a json file preset with variables that are received from the user from input().The only method I found sorta-similar to mine is here, but it doesnt show how to generate a new json file.

An example of inputs:

Enter the name of the json file:
>>>file

Enter the width:
>>>2

Enter the height:
>>>2

Then these inputs are converted into a json file like so:

{
    "width": "2",
    "height": "2"
    "column": [
        {
            "0": "1255255255"
            "1": "1255255255"
        },
        {
            "0": "1255255255"
            "1": "1255255255"
        }
    ]
}

Every list of values correspond to a column, and the values within a list are a row. How would I generate enough columns and rows to match the width and height?

i.e. a column:

        {
            "0": "1255255255"
            "1": "1255255255"
        }

a row:

            "0": "1255255255"

the "1255255255" value doesnt matter, it's just a placeholder.

crazicrafter1
  • 309
  • 5
  • 18

2 Answers2

2

You just need to produce a python representation (lists + dicts etc.) of the structure you want and then use the json library to dump it to a file.

So in your case,

import json

# Get these from input
filename = "test.json"
width = 3
height = 5
placeholder = 1255255255

obj = {
    "width": width,
    "height": height,
    "column": [{row: placeholder for row in range(height)} for col in range(width)]
}

with open(filename, "w") as out_file:
    json.dump(obj, out_file)
James Elderfield
  • 2,389
  • 1
  • 34
  • 39
  • 1
    Probably typo in your code - file shall be opened for writing `"w"`instead of reading `"r"`, otherwise `FileNotFoundError` or `io.UnsupportedOperation: not writable` is raised. – Bojan P. Dec 17 '17 at 07:56
1

I used list and dict comprehension to generate desired number of dictionaries with desired number of keys, then I used json.dump to serialize dictionary to JSON formatted string (while providing indent parameter, otherwise generated JSON would be just one line) and saved that string to the file opened with context manager (the preferred way to open files).

import json
import os

filename = input("Enter the name of the json file: ")
width = int(input("Enter the width: "))
height = int(input("Enter the height: "))

# Append .json if user did not provide any extension
if not os.path.splitext(filename)[1]:
    filename += ".json"

with open(filename, 'w') as f:
    json.dump({
        "width": width,
        "height": height,
        "column": [
            {
                str(row_idx): 0 for row_idx in range(height)
            }
            for column_idx in range(width)
        ]
    }, f, indent=4)

print("JSON saved to file {}".format(os.path.abspath(filename)))

Testing:

Enter the name of the json file: test_json
Enter the width: 2
Enter the height: 2
JSON saved to file C:\Users\Bojan\.PyCharm2017.3\config\scratches\test_json.json

Content of the test_json.json file:

{
    "width": 2,
    "height": 2,
    "column": [
        {
            "0": 0,
            "1": 0
        },
        {
            "0": 0,
            "1": 0
        }
    ]
}
Bojan P.
  • 942
  • 1
  • 10
  • 21