Reputation: 83
I'm trying to build a dynamic request in python and send it but I'm getting the error - "There was a problem in the JSON you submitted: lexical error: invalid char in json text."
My code:
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'auth_token ' + auth_token,
}
data = '{\n "datapoint": {\n "value": ' + val + ',\n "metadata": {\n " key1": "",\n "key2": ""\n }\n }\n}'
response = requests.post(url, headers=headers, data=data)
However, if I send a hardcoded value, the request is succesful:
data = '{\n "datapoint": {\n "value": "120",\n "metadata": {\n "key1": "",\n "key2": ""\n }\n }\n}'
How do I set the value using a variable 'val'?
Upvotes: 1
Views: 595
Reputation: 3107
Stop using that way to transform data to string, you need json.dumps()
.
import json
data = {"A":1,
"B":2
}
to_str = json.dumps(data)
print(type(to_str),to_str)
# <class 'str'> {"A": 1, "B": 2}
Upvotes: 1