将变量关联到Python json值

时间:2018-09-18 06:57:45

标签: python api django-rest-framework python-3.5

如果我有一个python json,并且想为python json中的值之一分配一个变量,

if booking.hotel.feedback_option == True:
                name = request.GET.get('firstname')
                email= request.GET.get('email')
                values = """
                  {
                    "Name" ="'+str(name)+'",
                    "HasExternalDoubleOptIn": true,
                    "Email"="'+str(email)+'",
                    "CustomFields": [
                    "Checkout=2018-09-07"
                    ]
                  }
                """
                headers = {
                  'Content-Type': 'application/json',
                  'Accept': 'application/json'
                }
                data = values.encode()
                req = Request('https://api.moosend.com/v3/subscribers/7c343r9ad-er56-4c51-810e-74e27f8505c2/subscribe.json?apikey=77f343914-4t3c-4d61-8435-9346f5b4adf6', data=data, headers=headers)
                response_body  = urlopen(req).read()

2 个答案:

答案 0 :(得分:1)

IIUC,更好的方法是创建一个python字典,然后转换为JSON:

import json

name = 'Something'
email = 'Something else'

values = {
          "Name": name,
          "HasExternalDoubleOptIn": True,
          "Email": email,
          "CustomFields": [
                    "Checkout=2018-09-07"
                    ]
          }

values = json.dumps(values)

答案 1 :(得分:0)

字典初始化程序中的第一个值语法错误-应该是一行 ”Name”: str(name), 相似地 ”Email”: str(email),