我正在尝试使用Zinc API编写Python脚本来购买亚马逊(请参阅:https://zinc.io/docs/#full-api)。我应该能够通过一个POST请求执行此操作,因此我阅读了有关urllib和urllib2 here的信息。
但是,当我运行脚本时,我收到此错误:
{"_type":"error","code":"invalid_json","message":"The JSON in your request could not be parsed."}
我非常准确地关注了Zinc的代码,所以我不确定为什么我会收到错误。
以下是我正在运行的内容(注意:我的个人信息被排除在外,但在我运行脚本时包括在内):
import urllib
import urllib2
import json
url = 'https://api.zinc.io/v0/order'
values = {"client_token" : "public",
"retailer" : "amazon",
"products" :[{"product_id" : "0679753354", "quantity" : 1}],
"max_price" : 1700, "shipping_address" : {
"first_name" : "NAME",
"last_name" : "NAME",
"address_line1" : "ADDRESS",
"address_line2" : "",
"zip_code" : "ZIP",
"city" : "CITY",
"state" : "STATE",
"country" : "US"
},
"is_gift" : False,
"shipping_method" : "cheapest",
"payment_method" : {
"name_on_card" : "NAME",
"number" : "CARDNUMBER",
"security_code" : "SECCODE",
"expiration_month" : 1,
"expiration_year": 2015
},
"billing_address" : {
"first_name" : "NAME",
"last_name" : "NAME",
"address_line1" : "ADDRESS",
"address_line2" : "",
"zip_code" : "ZIP",
"city" : "CITY",
"state" : "STATE",
"country" : "US",
"phone_number" : "PHONE"
},
"retailer_credentials" : {
"email" : "EMAIL",
"password" : "PASSWORD"}
}
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
print the_page
关于如何解决这个JSON解析问题的任何想法都会非常感激,因为我还没能弄清楚错误是什么。
答案 0 :(得分:2)
您不想对该数据进行urlencode。这是表单值,而不是JSON。
此外,您已导入json
模块,但您未在数据上使用该模块。你应该这样做:
data = json.dumps(values)
req = urllib2.Request(url, data, {'content-type': 'application/json'})
虽然使用第三方requests库更容易也更好。
答案 1 :(得分:2)
您正在对您的请求进行网址编码,但不会将Python数据转换为服务器可以理解的JSON。您应该调用json.dumps(values)而不是调用urllib.urlencode(values)。
例如:
import urllib
import urllib2
import json
url = 'https://api.zinc.io/v0/order'
values = {"client_token" : "public",
"retailer" : "amazon",
"products" :[{"product_id" : "0679753354", "quantity" : 1}],
"max_price" : 1700, "shipping_address" : {
"first_name" : "NAME",
"last_name" : "NAME",
"address_line1" : "ADDRESS",
"address_line2" : "",
"zip_code" : "ZIP",
"city" : "CITY",
"state" : "STATE",
"country" : "US"
},
"is_gift" : False,
"shipping_method" : "cheapest",
"payment_method" : {
"name_on_card" : "NAME",
"number" : "CARDNUMBER",
"security_code" : "SECCODE",
"expiration_month" : 1,
"expiration_year": 2015
},
"billing_address" : {
"first_name" : "NAME",
"last_name" : "NAME",
"address_line1" : "ADDRESS",
"address_line2" : "",
"zip_code" : "ZIP",
"city" : "CITY",
"state" : "STATE",
"country" : "US",
"phone_number" : "PHONE"
},
"retailer_credentials" : {
"email" : "EMAIL",
"password" : "PASSWORD"}
}
req = urllib2.Request(url, json.dumps(values))
response = urllib2.urlopen(req)
the_page = response.read()
print the_page