简体   繁体   中英

Python Post json API without Request

I am on a system without pip and its not planned to use. Put I have do to a post with python to an API (With this post I want to add a row in a postgresdb)

it works with the following code. but there are two columns which are jsonb in postgres. With this code these columns have quotation marks, so the json doesn't work properly.

How can I avoid this?

  import urllib.parse
import urllib.request
def_post_wo_requ
        json_post= { 'store' : 'Jack', 'store_detail' : {'Tel1':'00000','Tel2':'11111'}}
        url=host+'/'+ pg_table
        data = urllib.parse.urlencode(json_post)
    
        data = data.encode('utf-8')
        print(data)

The print data shows this:

b'store=Jack&store_detail=%7B%27Tel1%27%3A+%2700000%27%2C+%27Tel2%27%3A+%2711111%27%7D'

and the json in the db is this:

"{'Tel1': '00000', 'Tel2': '11111'}"

Do you need to convert the data to a string? Would not this ("classic" approach) work ?

from urllib import request
import json

url = 'https://myapp.domain/endpoint'
json_data= {'store': 'Jack', 'store_detail': {'Tel1': '00000','Tel2': '11111'}}

req = request.Request(url, method="POST")
req.add_header('Content-Type', 'application/json')
data = json.dumps(data)
data = data.encode()
r = request.urlopen(req, data=data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM