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
Answer from Karl on Stack Overflow
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
Convert a Python object containing all the legal data types: import json x = { "name": "John", "age": 30, "married": True, "divorced": False, "children": ("Ann","Billy"), "pets": None, "cars": [ {"model": "BMW 230", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1} ] } print(json.dumps(x)) Try it Yourself » · The example above prints a JSON string, but it is not very easy to read, with no indentations and line breaks.
Discussions

Convert string to JSON in Python? - Stack Overflow
I'm trying to convert a string, generated from an http request with urllib3. Traceback (most recent call last): File " ", line 1, in data = json.load(data) ... More on stackoverflow.com
🌐 stackoverflow.com
Sending my python object as proper JSON text
What you've got in that block isn't valid JSON - JSON needs to be in a key-value pair structure. The values can be complex objects, but each key only has one value defined. If you're doing this in Python there will be a library available to serialize your object into a JSON string. More on reddit.com
🌐 r/learnprogramming
4
1
April 6, 2022
How to retrieve JSON information through jinja
json.dumps(produce_list) does, in fact, turn the produce_list into a string. Just do return render_template("template.html", produce_list = produce_list) and you'll get what you are looking for. More on reddit.com
🌐 r/flask
2
5
May 27, 2017
Backslash escaping in the launch.json args
Found the solution: "args": [ "test", "`echo -n \"${relativeFileDirname}\" | tr \\\\ .`.${fileBasenameNoExtension}" ], You need to quote the variable substitution. More on reddit.com
🌐 r/vscode
1
2
June 8, 2020
People also ask

What's the fastest way to parse JSON in Python?
For most workloads, the standard json module is fast enough. For high-throughput parsing (>10K parses/sec), use orjson or ujson — both are 2-10× faster. orjson handles datetimes, UUIDs, and dataclasses natively; ujson is more compatible with the standard library API. Both have C-extension speed.
🌐
spyderproxy.com
spyderproxy.com › home › blog › python string to json
SpyderProxy | Premium Residential, Datacenter & LTE Proxies
Can json.loads() parse bytes directly in Python 3?
Yes, since Python 3.6. json.loads(b'{"a":1}') works. The bytes must be UTF-8, UTF-16, or UTF-32 (auto-detected). For other encodings, decode first: json.loads(bytes_data.decode('latin-1')).
🌐
spyderproxy.com
spyderproxy.com › home › blog › python string to json
SpyderProxy | Premium Residential, Datacenter & LTE Proxies
How do I validate a JSON string against a schema?
Two options: (1) jsonschema library — define a JSON Schema document, validate any parsed JSON against it; (2) pydantic — define Python models with type hints, parse and validate in one step. Pydantic is faster and produces typed Python objects; jsonschema is the standard for schema documents shared across languages.
🌐
spyderproxy.com
spyderproxy.com › home › blog › python string to json
SpyderProxy | Premium Residential, Datacenter & LTE Proxies
🌐
Programiz
programiz.com › python-programming › json
Python JSON: Read, Write, Parse JSON (With Examples)
If you do not know how to read and write files in Python, we recommend you to check Python File I/O. You can convert a dictionary to JSON string using json.dumps() method.
🌐
SpyderProxy
spyderproxy.com › home › blog › python string to json
SpyderProxy | Premium Residential, Datacenter & LTE Proxies
May 4, 2026 - Quick verdict: Use json.loads(s) to convert a Python string to JSON. The result is a dict, list, or scalar depending on the JSON type. Wrap in try/except for json.JSONDecodeError.
🌐
GeeksforGeeks
geeksforgeeks.org › python-ways-to-convert-string-to-json-object
Convert String to JSON Object - Python - GeeksforGeeks
This resulting dictionary is assigned to the variable res. ast.literal_eval() function safely evaluates a string containing Python literals (including JSON-like structures) and converts it into an equivalent Python object.
Published: April 15, 2025
Find elsewhere
🌐
iProyal
iproyal.com › blog › python-string-to-json
How to Convert a Python String to JSON (Beginner’s Guide)
August 18, 2025 - To fix it, make sure every key is paired with a valid Python expression or value. All nested objects or multiple key-value pairs should be valid. Make sure lists and dictionaries nest properly. A malformed JSON object can break your app or API call, so always validate your structure before sending or parsing it. Now you know how to use the JSON module to convert between JSON strings and Python objects.
🌐
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 - This comes built-in to Python and is part of the standard library. So, say you have a file named demo.py. At the top you would add the following line: ... #include json library import json #json string data employee_string = '{"first_name": "Michael", "last_name": "Rodgers", "department": "Marketing"}' #check data type with type() method print(type(employee_string)) #output #<class 'str'>
🌐
TecAdmin
tecadmin.net › how-to-convert-string-to-json-in-python
How to Convert String to JSON in Python – TecAdmin
April 26, 2025 - Here, json_string is the string that you want to convert to JSON, and json_object is the resulting Python object. Let’s see an example of this: ... In this example, we pass a JSON string to the loads() method, which returns a Python object that represents the JSON data.
🌐
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().
🌐
Scaler
scaler.com › home › topics › string to json python
Convert String to JSON in Python - Scaler Topics
December 4, 2023 - This function accepts a Python object and produces a JSON string as its output. Decoding (deserializing) JSON: To change a JSON string into a Python object, the json.loads() function is used.
🌐
Bomberbot
bomberbot.com › python › python-json-how-to-convert-a-string-to-json
Python JSON – How to Convert a String to JSON - Bomberbot
April 22, 2024 - By passing the custom_decoder function as the object_hook parameter to json.loads(), we can automatically convert specific fields to their desired data types during decoding. When working with large JSON datasets, performance becomes a critical factor. The json module in Python is implemented in C, making it efficient for most use cases. However, there are a few considerations to keep in mind: Parsing large JSON strings can be memory-intensive.
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
July 21, 2026 - As a Python developer, you may need to pay extra attention to the Boolean values. Instead of using True or False in title case, you must use the lowercase JavaScript-style Booleans true or false. Unfortunately, there are some other details in the JSON syntax that you may stumble over as a developer. You’ll have a look at them next. The JSON standard doesn’t allow any comments, trailing commas, or single quotes for strings.
🌐
Linux Hint
linuxhint.com › convert-a-string-to-json-python
Linux Hint – Linux Hint
April 24, 2023 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
ReqBin
reqbin.com › code › python › pbokf3iz › python-json-dumps-example
How to dump Python object to JSON using json.dumps()?
To dump a Python object to JSON string, you can use the json.dumps() method of the built-in json module.
🌐
GitHub
gist.github.com › craigsdennis › 0f00869fe2e2f2da9d6287984c62b2af
Convert Python String to JSON · GitHub
Convert Python String to JSON · Raw · pythonDictParser.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Zyte
zyte.com › home › blog › json parsing with python [practical guide]
JSON Parsing with Python [Practical Guide]
December 3, 2024 - Here is the CarDecoder class, which will allow us to pass data as JSON string and return the custom python object.