Answer the question
In order to leave comments, you need to log in
How to insert a variable into JSON?
Hi all!
I don’t understand Python, but I need to write a small script that sends JSON to the API
I don’t understand how to insert a variable (base64 file) into JSON
Code piece:
image_url = "https://mail.ru/pass.jpg"
with urllib.request.urlopen(image_url) as image_file:
encoded_string = base64.b64encode(image_file.read())
batch = {
"Id": "b1g",
"cs": [
{
"content": encoded_string,
"features": [
{
"tp": "TX",
"text": {
"lang": [
"*"
],
"md": "pass"
}
}
]
}
]
}
resp = requests.post("https://yam.net/v1/Analyze", json=batch ).json()
Answer the question
In order to leave comments, you need to log in
Problem solved.
UTF-8 is used in json, I encode the file in base64, I get a variable in bytes
To convert to a string, you need to add
Yes and addencoded_string = encoded_string.decode("UTF-8")
batch["cs"][0]["content"] = encoded_string
What is your JSON? What you need? Word to list, key with value??? In what JSON? You actually have two.
JSON is a dictionary. Unlike a list, where you can only add the next element/s through the built-in append/extend functions or through +=, you can add/rewrite to a dictionary by simply specifying the key with the path from the beginning of the dictionary and the value of this key.
dict1['level1']['level2']['level3']=999
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question