Google App Engine:Python:WebOb:如何以JSON格式获取POST数据? [英] Google App Engine: Python: WebOb: How to get POST data in JSON format?

查看:360
本文介绍了Google App Engine:Python:WebOb:如何以JSON格式获取POST数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Google App Engine平台上构建了一个Web应用程序,该平台使用使用WebOb的webapp2。我想以 POST 一些JSON格式的数据,包括嵌套数组和字典。例如:

  $。post('/ addvendor',{'vendor':{'name':'test','描述':'好公司','tags':['foo','bar']}},function(data){console.log(data)},'application / json')

但是,在服务器端,数据以平面MultiDict对象形式出现,与原始嵌套的JSON对象我 POST 编辑。例如:

 >>>打印self.request.params.items()
[(u'vendor [name]',u'test'),(u'vendor [description]',u'a good company'),(u' vendor [tags] []',u'foo'),(u'vendor [tags] []',u'bar')]

这个对象很难解析。在我的服务器代码中,有没有办法在服务器上获得标准JSON格式的相同数据,或者至少是一个使用嵌套字典和数组的Python等效数据,以便我可以轻松操作和检查数据?

你应该使用$ .ajax并手动设置contentType ='application / json; charset = utf-8',而不是因为$ .post使用默认的application / x-www-form-urlencoded;内容类型。您还需要使用JSON.stringify手动将数据编码为JSON字符串:

  $。ajax({url:'/ addvendor ',
type:'post',
data:JSON.stringify({'vendor':{'name':'test','description':'好公司','tags': ['foo','bar']}}),
contentType:'application / json; charset = utf-8',
dataType:json,
success:function(data ){console.log(data)}})

...

print json.loads(self.request.body)


I am building a web app on the Google App Engine platform, which uses webapp2, which uses WebOb. I would like to POST some data in JSON format, including nested arrays and dictionaries. E.g.:

$.post('/addvendor', {'vendor': {'name': 'test', 'description': 'a good company', 'tags':['foo', 'bar']}}, function(data){console.log(data)}, 'application/json')

However, on the server side, the data comes in as a flat "MultiDict" object, not anything like the original nested JSON object that I POSTed. E.g.:

>>> print self.request.params.items()
[(u'vendor[name]', u'test'), (u'vendor[description]', u'a good company'), (u'vendor[tags][]', u'foo'), (u'vendor[tags][]', u'bar')]

This object is very difficult to parse. In my server code, is there a way to get the same data in standard JSON format, or at least a Python equivalent using nested dictionaries and arrays, on the server so that I can manipulate and examine the data easily?

解决方案

(updated with jayhendren's help) You should use $.ajax and manually set contentType='application/json; charset=utf-8' instead because $.post uses default "application/x-www-form-urlencoded;" content type. Also you need to manually encode data to JSON-string with JSON.stringify:

$.ajax({url:'/addvendor', 
        type: 'post', 
        data:JSON.stringify({'vendor': {'name': 'test', 'description': 'a good company', 'tags':['foo', 'bar']}}), 
        contentType:'application/json; charset=utf-8',
        dataType: "json",
        success:function(data){console.log(data)}})

...

print json.loads(self.request.body)

这篇关于Google App Engine:Python:WebOb:如何以JSON格式获取POST数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆