You're escaping the inner double quote " in your string. It should be:

b"{\"Machine Name\":\""+hostname+"\"}", None, True)

In python you can also use single quotes ' for strings - and you don't need to escape double quotes inside single quoted strings

b'{"Machine Name":"'+hostname+'"}', None, True)

There are two better ways of doing this though. The first is string formatting which inserts a variable into a string:

b'{"Machine Name":"%s"}' % hostname # python 2.x (old way)
b'{{"Machine Name":"{0}"}}'.format(hostname) # python >= 2.6 (new way - note the double braces at the ends)

The next is with the Python JSON module by converting a python dict to a JSON string

>>> hostname = "machineA.host.com"
>>> data = {'Machine Name': hostname}
>>> json.dumps(data)
'{"Machine Name": "machineA.host.com"}'

This is probably the preferred method as it will handle escaping weird characters in your hostname and other fields, ensuring that you have valid JSON at the end.

Is there a reason you're using a bytestring

Answer from Peter Gibson on Stack Overflow
🌐
Python Examples
pythonexamples.org › python-create-json
Python Create JSON
In Python, you can create JSON string by simply assigning a valid JSON string literal to a variable, or convert a Python Object to JSON string using json.loads() function. In this tutorial, we will create JSON from different types of Python objects. In this example, we will create JSON formatted ...
Discussions

Passing a Python string into JSON payload - Stack Overflow
I've tried just with single quotes and no plus signs, just the variable name, without the comma at the end. I'm just stumbling round in the dark, really. ... The reason your string isn't working is because you used double quotes " for the string instead of single quotes '. Since json format ... More on stackoverflow.com
🌐 stackoverflow.com
python - Create JSON object with variables from an array - Stack Overflow
I want to create a JSON object with an array and I can't seem to solve the problem. The problem I'm having is that it only assigns the last index value to my variable.Can someone show me how to ass... More on stackoverflow.com
🌐 stackoverflow.com
Generating Json file with custom variables Python - Stack Overflow
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... More on stackoverflow.com
🌐 stackoverflow.com
December 16, 2017
python - How to dynamically create a JSON string? - Stack Overflow
I am trying to create a JSON string that I can send in a PUT request but build it dynamically. For example, once I am done, I'd like the string to look like this: { "request-id": 1045058, ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
YouTube
youtube.com › codinggpt
python create json string with variables - YouTube
Instantly Download or Run the code at https://codegive.com creating a json string with variables in python: a step-by-step tutorialjson (javascript object n...
Published: February 25, 2024
Views: 4
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... JSON is a syntax for storing and exchanging data. JSON is text, written with JavaScript object notation.
Top answer
1 of 2
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)
2 of 2
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
        }
    ]
}
Find elsewhere
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
July 21, 2026 - After importing the json module, you can use .dumps() to convert a Python dictionary to a JSON-formatted string, which represents a JSON object. It’s important to understand that when you use .dumps(), you get a Python string in return. In other words, you don’t create any kind of JSON data type.
🌐
Stack Overflow
stackoverflow.com › questions › 70959729 › how-to-create-a-python-variable-from-a-json-format › 70961235
How to create a python variable from a json format - Stack Overflow
There's no problem with the send/receive procedures, all the messages are sent and received between the client and the server. I just want to know if we can create a global variable from this. ... Save this answer. ... Show activity on this post. You can use the global keyword to modify a global variable from inside the function thar receives the data: Copyvariable_data = {} def receive_data(interface): global variable_data variable_data = interface.recv_json()
🌐
freeCodeCamp
freecodecamp.org › news › python-json-how-to-convert-a-string-to-json
Python JSON – How to Convert a String to JSON
November 9, 2021 - // It defines the first name and last name of an employee · To use JSON with Python, you'll first need to include the JSON module at the top of your Python file. This comes built-in to Python and is part of the standard library.
🌐
Towards Data Science
towardsdatascience.com › home › latest › how to handle json in python
How to handle JSON in Python | Towards Data Science
January 16, 2025 - Note: Remember for the conversion of the Python objects into a JSON string you need to use dumps(). First, let us create four different types of variables which can hold the above python data
🌐
Reddit
reddit.com › r/learnpython › write json file to variable in python
r/learnpython on Reddit: write json file to variable in python
August 24, 2023 -

I have a file

state_info.txt

state1: New york
size: 302.6 mi²
state2: connecticut
size2: 5,028 mi²

What im trying to do is take the content in this file and convert it to json and save it as

a python variable named JSON_DUMP so that I can use it for a request to post a message

READFILE = open('state_info.txt', "r")

JSON_DUMP = print(READFILE.read())

print(f'Sending to geography channel')

SEND_MSG = requests.post(url=WEBHOOK, json=JSON_DUMP) print(SEND_MSG)

However, this gives me a 400 error and i'm not sure why.

If I use this variable below

JSON_STUFF = {"text": 'US States Information provided'}
SEND_MSG = requests.post(url=WEBHOOK, json=JSON_STUFF)

print(SEND_MSG)

I get a 200 and the message gets sent so I know the WEBHOOK works properly and message will send but the state_info.txt file may change when more people add information to it.

Is there a way to take the contents of a file and save it as JSON "variable" for python to then use in a request response?

There seems to be ways to save data to a file, take variables and write them to files, but im trying to do the opposite? Anyone know if this could be done?

🌐
GeeksforGeeks
geeksforgeeks.org › python › build-a-json-object-in-python
Build a Json Object in Python - GeeksforGeeks
July 23, 2025 - In this article, we'll explore how to create and build JSON objects in Python. Below are some of the ways by which we can build a JSON object in Python: ... JSON module is imported to deal with JSON objects. A Python dictionary named 'data' is used to store the object in key-value pairs. json.dumps( ) is used convert the Python dictionary into JSON formatted string and result is displayed.
🌐
Checkmk
forum.checkmk.com › troubleshooting
REST API: Python question: How to use variables in "json={" post in key and value? - Troubleshooting - Checkmk Forum
October 24, 2022 - CMK version:2.0.0p26 OS version:RHEL 8 Hello Python Experts: I need your help to add a server via REST API by using variables for the keys and values. In general it works but I need some help to get the right syntax for the key and value definitions by using variables.
🌐
Reddit
reddit.com › r/learnpython › how can i replace these json values with variables?
r/learnpython on Reddit: How can I replace these json values with variables?
January 16, 2021 -

I am trying to make a python script which generates json. I know bash but not python.

I know this is easy, but I cannot figure it out. How do I replace these values with variables? I guess I don't how to call a variable like you can like this in bash: $variable

Thanks.

import json

person_json = {
"name": "Fred",
"place": "Melbourne",
"sex": "male",
"remote": { "addr": "Acacia Avenue", "id": "875932875392" },
"local": { "id": "8475974", "office": "Main" }
}
🌐
LearnPython.com
learnpython.com › blog › json-in-python
How to Convert a String to JSON in Python | LearnPython.com
The dumps() method converts a Python object to a JSON formatted string. We can also create a JSON file from data stored in a Python dictionary. The method for performing this task is dump(). Let’s use the dump() method for creating a JSON file.
🌐
W3Schools
w3schools.com › python › gloss_python_convert_into_JSON.asp
Python Convert From Python to JSON
Remove List Duplicates Reverse ... ... If you have a Python object, you can convert it into a JSON string by using the json.dumps() method....