I have the following code:
import json
domain="abc.com"
rawlog = json.loads(
f'{"domain": ${domain}}')
print(rawlog["domain"])
Which gives me:
Traceback (most recent call last):
File "<string>", line 6, in <module>
ValueError: Invalid format specifier
>
The question is, what is the cause and if I can have fstring in Json? I'm using the newest Python: python3 --version shows Python 3.10.4.
I also tried:
import json
domain="abc.com"
rawlog = json.loads('{"domain": f'{domain}'}')
print(rawlog["domain"])
but it gives:
File "<string>", line 5
rawlog = json.loads('{"domain": f'domain'}')
^
SyntaxError: invalid syntax
As { and } have special meaning they need to be escaped to mean literal { and literal }, consider following simple example
import json
domain="abc.com"
string=f'{{"domain": "{domain}"}}'
parsed=json.loads(string)
print(parsed)
gives output
{'domain': 'abc.com'}
Related
While reading a JSON and trying to evaluate, a syntax error is returned.
json file has the below data
{
"communication":{
"xml":{
"xmlData": "<test vers=\"1.0\" >random</test>",
"user_id":"123456789"
},
},
}
Code snippet :
import ast
.
.
#json_file is the python obj which consists the data read from json file
.
val = ast.literal_eval(json.dumps(json_file))
print(val)
Error thrown :
Traceback (most recent call last):
File "./prog.py", line 12, in <module>
File "/usr/lib/python3.8/ast.py", line 59, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/lib/python3.8/ast.py", line 47, in parse
return compile(source, filename, mode, flags,
File "<unknown>", line 4
"xmlData": "<test vers="1.0" >random</test>",
^
SyntaxError: invalid syntax
Please suggest a way to resolve the syntax error. Note that changing vers="1.0" to vers='1.0' would have fixed the issue but I do not have write access to this JSON file. My application is just reading the data.
Your json is invalid, if you cant modify the file then modify the data in python.
corrected json
{
"communication":{
"xml":{
"xmlData":"<test vers=\"1.0\" >random</test>",
"user_id":"123456789"
}
}
}
my code
import json
import ast
fd = open("text.json")
json_file = json.load(fd)
val = ast.literal_eval(json.dumps(json_file))
print(val)
output
{'communication': {'xml': {'xmlData': '<test vers="1.0" >random</test>', 'user_id': '123456789'}}}
I'm trying to take the string hello, encode it into hexadecimal, and then print success if the value of t is found in the encoded string.
This is what I have currently:
import codecs
t='68656c6c6df'
pkts = ("hello")
pkts1 = codecs.encode(b'hello', 'hex_codec')
if "t" in pkts1:
print ('success')
Which gives me the error:
Traceback (most recent call last):
File "C:/Users/K/.PyCharmCE2018.1/config/scratches/scratch_1.py", line 8, in <module>
if "t" in pkts1:
TypeError: a bytes-like object is required, not 'str'
my script includes this line:
encoded = "Basic " + s.encode("base64").rstrip()
But gives me back the error:
LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs
This line seemed to work fine in python 2 but since switching to 3 I get the error
This string codec was removed in Python 3. Use base64 module:
Python 3.6.1 (default, Mar 23 2017, 16:49:06)
>>> import base64
>>> base64.b64encode('whatever')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'
>>> base64.b64encode(b'whatever')
b'd2hhdGV2ZXI='
>>>
Don't forget to convert the data to bytes.
Code as follows:
base64.urlsafe_b64encode('Some String'.encode('UTF-8')).decode('ascii')
For example: return {'raw': base64.urlsafe_b64encode(message.as_string().encode('UTF-8')).decode('ascii')}
Worked for me.
My python version is 3.4, below is the error message.
Traceback (most recent call last):
File "test.py", line 1, in <module
from avs_client import AlexaVoiceServiceClient
File "/home/mstts/Documents/Amazon/alexa-voice-service-client/avs_client/__init__.py", line 1, in <module
from avs_client.avs_client.client import AlexaVoiceServiceClient
File "/home/mstts/Documents/Amazon/alexa-voice-service-client/avs_client/avs_client/client.py", line 5, in <module
from avs_client.avs_client import authentication, connection, device, ping
File "/home/mstts/Documents/Amazon/alexa-voice-service-client/avs_client/avs_client/connection.py", line 64
**authentication_headers,
^
SyntaxError: invalid syntax
And below is code segment which raises the error.
headers = {
**authentication_headers,
'Content-Type': multipart_data.content_type
}
Thanks for anyone who could be as kind to let me know what I am doing wrong and why that would be great!
This additional unpacking syntax for dictionary literals was introduced in Python 3.5 (see PEP-448); in earlier versions, it’s a syntax error. If you cannot upgrade, you will have to create the headers in two steps, e.g.:
headers = {'Content-Type': multipart_data.content_type}
headers.update(**authentication_headers)
as suggested by Ozgur in the comments.
I wrote an algorithm using python and matplotlib that generates histograms from some text input data. When the number of data input is approx. greater than 15000, I get in the (append) line of my code:
mydata = []
for i in range(len(data)):
mydata.append(string.atof(data[i]))
the error:
Traceback (most recent call last):
File "get_histogram_picture.py", line 25, in <module>
mydata.append(string.atof(data[i]))
File "/usr/lib/python2.6/string.py", line 388, in atof
return _float(s)
ValueError: invalid literal for float(): -a
can it be an error in python ? What is the solution ?
Thanks
That's a data parsing error:
>>> float("-a")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): -a
Python data structure size if only limited by the available memory.