开发者

jquery: post with json will actually post array

开发者 https://www.devze.com 2023-01-24 12:28 出处:网络
I have a python as CGI and the POST from jquery will transform json object to array, so when开发者_运维知识库 I see the POST from jquery, I actually see:

I have a python as CGI and the POST from jquery will transform json object to array, so when开发者_运维知识库 I see the POST from jquery, I actually see:

login_user[username]=dfdsfdsf&login_user[password]=dsfsdf

(the [ and ] already escaped)

My question is how I can convert this string back to JSON in python? Or, how can I convert this string to python array/dict structure so that I can process it easier?

[edit] My jquery is posting:

{'login_user': {'username':username, 'password':password}}


If what you want to accomplish is to send structured data from the browser and then unpack it in your Python backend and keep the same structure, I suggest the following:

  1. Create JavaScript objects in the browser to hold your data:

    var d = {} 
    d['login_user'] = { 'username': 'foo', 'password': 'bar' }
    
  2. Serialize to JSON, with https://github.com/douglascrockford/JSON-js
  3. POST to your backend doing something like this:

    $.post(url, {'data': encoded_json_data}, ...)

  4. In your Python code, parse the JSON, POST in my example is where you get your POST data in your CGI script:

    data = json.loads(POST['data'])
    data['login_user']
    


import re

thestring = "login_user[username]=dfdsfdsf&login_user[password]=dafef"

pattern = re.compile(r'^login_user\[username\]=(.*)&login_user\[password\]=(.*)')
match = pattern.search(thestring)
print match.groups()

Output: >>> ('dfdsfdsf', 'dafef')

Thus,

lp = match.groups()
print "{'login_user': {'username':"+lp[0]+", 'password':"+lp[1]+"}}"

shall bear: >>> {'login_user': {'username':dfdsfdsf, 'password':dafef}}


>>> import json
>>> data = {'login_user':{'username':'dfdsfdsf', 'password':'dsfsdf'}}
>>> json.dumps(data)
'{"login_user": {"username": "dfdsfdsf", "password": "dsfsdf"}}'

I suspect that data would already be contained in a GET var if that's coming from the URL...

0

精彩评论

暂无评论...
验证码 换一张
取 消