1

I'm starting to get into Python lately and was wondering if you could post some code about how to to encode a JSON string, send it as an HTTP request to a URL, and parse the response.

Here's some code I've been playing around with:

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
  • 2
    None of the code shows even an attempt at this. Commented Jul 30, 2012 at 22:08
  • I suppose you could uses requests docs.python-requests.org/en/latest/index.html to send and receive it. I'm not sure how requests handles sending JSON though. Commented Jul 30, 2012 at 22:12

2 Answers 2

4

I wrote an answer to do such a thing for the github api the other day. See my answer here.

In essence, the code boiled down to:

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())
Sign up to request clarification or add additional context in comments.

2 Comments

thanks man. All I wanted was this simple breakdown. Now, time to put it to work.
This is actually using Python 2, while the question states it is using Python 3.
1

The modules you'll want are httplib or http.client, depending on your version of Python, and json. In JSON, the simple loads and dumps functions should encode and decode JSON easily for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.