带有JSON的帖子实际上将发布数组

带有JSON的帖子实际上将发布数组

本文介绍了jQuery:带有JSON的帖子实际上将发布数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python作为CGI,来自jquery的POST会将json对象转换为数组,所以当我看到来自jquery的POST时,我实际上看到了:

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

([和]已转义)

我的问题是如何在python中将该字符串转换回JSON?或者,如何将这个字符串转换为python array/dict结构,以便我可以更轻松地处理它?

我的jquery正在发布:

{'login_user': {'username':username, 'password':password}}
解决方案

如果要完成的工作是从浏览器发送结构化数据,然后将其解压缩到Python后端并保持相同的结构,则建议以下操作:

  1. 在浏览器中创建JavaScript对象来保存数据:

    var d = {}
    d['login_user'] = { 'username': 'foo', 'password': 'bar' }
    

  2. 使用 https://github.com/douglascrockford/JSON-js 序列化为JSON
  3. POST到您的后端,执行以下操作:

    $.post(URL,{'data':encode_json_data},...)

  4. 在您的Python代码中,解析JSON,在我的示例中,POST是在CGI脚本中获取POST数据的地方:

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

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']
    

这篇关于jQuery:带有JSON的帖子实际上将发布数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 06:40