Try using triple curly braces. {{ gets converted to a string { (It is an escape sequence).
AccessToken = "AccessTokenValue"
payload={}
headers = { 'authorization': f'{{{AccessToken}}}'}
print(headers)
This will print: {'authorization': '{AccessTokenValue}'}
Python - Using .format() on a JSON string that already has curly braces '{ }' - Stack Overflow
Add variable value in a JSON string in Python - Stack Overflow
python - How do I escape curly-brace ({}) characters characters in a string while using .format? - Stack Overflow
Python and JSON with brackets
Videos
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"}'
You need to double the {{ and }}:
>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '
Here's the relevant part of the Python documentation for format string syntax:
Format strings contain “replacement fields” surrounded by curly braces
{}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling:{{and}}.
Python 3.6+ (2017)
In the recent versions of Python one would use f-strings (see also PEP498).
With f-strings one should use double {{ or }}
n = 42
print(f" {{Hello}} {n} ")
produces the desired
{Hello} 42
If you need to resolve an expression in the brackets instead of using literal text you'll need three sets of brackets:
hello = "HELLO"
print(f"{{{hello.lower()}}}")
produces
{hello}
Hallo Team,
I know why this is happening but unable to find a solution.
We all know JSON file always start with curly bracket "{" and ends with "}" but sometimes it can also start with square bracket "["
But when I run below code, it fails for obvious reasons
# Purpose: Create or delete or update json file
# Python program to update
# JSON
import json
x = '[{"certificateChain": "certdata", "resourceFqdn": "resourceFQDN"}]'
# python object to be appended
y = {"certificateChain": "lotofdata"}
# # parsing JSON string:
z = json.loads(x)
# # appending the data
z.update(y)
# # the result is a JSON string:
print(json.dumps(z))
Traceback (most recent call last):
File "/Users/poseidon/VCF/automation/python/basic_python_tasks/create_update_json.py", line 29, in <module>
z.update(y)
^^^^^^^^how to resolve this part?
You have to apply format to the string, not the dict that contains the string:
headers = {
{'X-Username':'user',
'X-Token':'{0}'.format(token_string)
}
}
And, you can't put a dict in a set; you'll have to use a list.
headers = [
{'X-Username':'user',
'X-Token':'{0}'.format(token_string)
}
]
You are getting that error because you are trying to put a dict in a Set.
Consider:
foo = {"a"} # type(foo) <class 'set'>
foo.add({"b": 1}) # throws unhashable error
{"a", {"b": 1}} # equivalent to the above 2 lines
This is a fairly common error since set literals and dict literals both use curly braces:
bar = {"a", 1, "b", 2} # oops! 4 element set instead of dict with 2 k/v pairs
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
I'm confused about the use of the curly brackets in this code from a textbook. I thought the curly brackets are to call dictionaries. but first and last are not, am I right?
def get_formatted_name(first,last):
full_name=f"{first}{last}"
return full_name.title()