S
S
Scorpic2020-09-27 23:25:17
Python
Scorpic, 2020-09-27 23:25:17

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()


What is the correct way to insert encoded_string variable into JSON?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Scorpic, 2020-09-28
@Scorpic

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

S
soremix, 2020-09-27
@SoreMix

What is your JSON? What you need? Word to list, key with value??? In what JSON? You actually have two.

P
PavelMos, 2020-09-28
@PavelMos

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 question

Ask a Question

731 491 924 answers to any question