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
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
instead of manipulating the string consider having the data as a python structure and then dump it to json
>>> d = {}
>>> d['Machine Name'] = hostname
>>> json.dumps(d)
'{"Machine Name": "machineA.host.com"}'
Passing a Python string into JSON payload - Stack Overflow
python - Create JSON object with variables from an array - Stack Overflow
Generating Json file with custom variables Python - Stack Overflow
python - How to dynamically create a JSON string? - Stack Overflow
The reason your string isn't working is because you used double quotes " for the string instead of single quotes '. Since json format requires double quotes, you only should be using double quotes inside the string itself and then use the single quotes to denote the start/end of a string. (That way you don't need to keep using those \" unnecessarily.
Also, .format() can help with putting variables inside strings to make them easier.
This should fix your json string:
targetTemp = 17
payload = '{\n "nodes": [{\n "attributes": {\n "targetHeatTemperature": {\n "targetValue": {},\n }\n }\n }]\n}'.format(targetTemp)
However, using the json module makes things a lot easier because it allows you to pass in a python dictionary which can be converted from/to a json string.
Example using the json package:
import json
targetTemp = 17
payload = {
"nodes": [{
"attributes": {
"targetHeatTemperature": {
"targetValue": targetTemp
}
}
}]
}
payload_json = json.dumps(payload) # Convert dict to json string
'+ targetTemp +' within the outermost double quotes isn't doing string concatenation. It's literally putting that text.
You should be using "+ targetTemp +"
However, building an actual dictionary, and using json.dumps will be less error-prone
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)
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
}
]
}
Create a normal python dictionary, then convert it to JSON.
raw_data = {
CONST_DB_NAME: getDbNameValue()
}
# ...
json_data = json.dumps(raw_data)
# Use json_data in your PUT request.
You can concat the string using + with variables.
CONST_REQUEST_ID = "request-id"
CONST_DB_CONNECTIONS = "db_connections"
CONST_DB_NAME = "db-name"
CONST_TABLE_NAME = "table-name"
request_id = "1045058"
db_name = "Sales"
table_name = 'customer'
json_string = '{' + \
'"' + CONST_REQUEST_ID + '": ' + request_id \
+ ',' + \
'"db-connections":' \
+ '[' \
+ '{' \
+ '"' + CONST_DB_NAME +'":"' + db_name + '",' \
+ '"' + CONST_TABLE_NAME + '":"' + table_name + '"' \
+ '}' \
+ ']' \
+ '}'
print json_string
And this is the result
python st_ans.py
{"request-id": 1045058,"db-connections":[{"db-name":"Sales","table-name":"customer"}]}
You build the object before encoding it to a JSON string:
import json
data = {}
data['key'] = 'value'
json_data = json.dumps(data)
JSON is a serialization format, textual data representing a structure. It is not, itself, that structure.
You can create the Python dictionary and serialize it to JSON in one line and it's not even ugly.
my_json_string = json.dumps({'key1': val1, 'key2': val2})
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?
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" }
}