1

我最近开始接触 Python,想知道您是否可以发布一些关于如何编码 JSON 字符串、将其作为 HTTP 请求发送到 URL 并解析响应的代码。

这是我一直在玩的一些代码:

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

2 回答 2

4

前几天我写了一个答案来为 github api 做这样的事情。在这里查看我的答案。

本质上,代码归结为:

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())
于 2012-07-30T22:09:56.317 回答
1

您需要的模块是httplibhttp.client,具体取决于您的 Python 版本,以及json. 在 JSON 中,simpleloadsdumps函数应该为您轻松编码和解码 JSON。

于 2012-07-30T22:09:45.633 回答