2012-07-30 20 views
1

最近我開始深入Python,想知道是否可以發佈一些關於如何對JSON字符串進行編碼的代碼,將它作爲HTTP請求發送到URL並解析響應。Python JSON調用

下面是一些代碼,我一直在玩弄:

import os 
import json 

if os.name == 'nt': 
    def clear_console(): 
     subprocess.call("cls", shell=True) 
     return 
else: 
    def clear_console(): 
     subprocess.call("clear", shell=True) 
     return 

def login_call(username, password): 

choice = 0 

while int(choice) not in range(1,2): 
    clear_console() 
    print ('') 
    print (' Json Calls - Menu') 
    choice = input(''' 
    1. Login. 

    Enter Option: ''') 

print ('') 

choice = int(choice) 

if choice == 1: 

    login_call(username, password) 
+2

代碼中沒有顯示,即使在這樣的一個嘗試。 – 2012-07-30 22:08:23

+0

我想你可以使用'requests' http://docs.python-requests.org/en/latest/index.html來發送和接收它。我不確定'request'如何處理髮送'JSON'。 – TankorSmash 2012-07-30 22:12:22

回答

4

我寫了一個答案,爲前些日子爲github api做了這樣的事情。見我answer here.

在本質上,代碼歸結爲:

import urllib2 
import json 


data = {"text": "Hello world github/linguist#1 **cool**, and #1!"} 
json_data = json.dumps(data) 

req = urllib2.Request("https://api.github.com/markdown") 
result = urllib2.urlopen(req, json_data) 

print '\n'.join(result.readlines()) 
+0

謝謝你。我只想要這個簡單的故障。現在,讓它開始工作。 – ASPiRE 2012-07-30 22:57:31

+0

這實際上是使用Python 2,而問題則指出它使用的是Python 3。 – 2014-08-12 14:27:36

1

你會想這些模塊httplibhttp.client,這取決於你的Python版本,並json。在JSON中,簡單的loadsdumps函數應該可以輕鬆地爲您編碼和解碼JSON。