将测试客户端数据转换为JSON

编程入门 行业动态 更新时间:2024-10-27 22:26:45
本文介绍了将测试客户端数据转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在构建一个应用程序,我想做一些测试。我需要将来自测试客户端的响应数据转换为JSON。

应用程序:

tasks = [ {'id':1,'title':u'Buy groceries','description':u'Milk,奶酪,比萨,水果,Tylenol','完成':False }, {'id':2,'title':u'Learn Python','description':u'需要在网上找到一个好的Python教程','done':False } ] app = Flask(__ name__,static_url_path =) @ app.route('/ myapp / api / v1.0 / tasks',methods = ['GET']))def get_tasks(): return jsonify({'tasks':[task for task in task]}) if __name__ =='__main__': app.run (debug = True)

测试:

class MyTestCase(unittest.TestCase): def setUp(self): myapp.app.confi g ['TESTING'] = True self.app = myapp.app.test_client() $ b $ def test_empty_url(self): response = self.app.get(' /myapp/api/v1.0/tasks') resp = json.loads(response.data) print(resp) if __name__ =='__main__': unittest.main()

当我尝试转换响应.data 到JSON,我得到以下错误:

TypeError:JSON对象必须是str ,而不是'字节'

如何解决这个错误并获取JSON数据?

解决方案

您需要获取响应数据作为文本,但默认是字节。响应对象提供了 get_data 来控制这个。

data = json.loads(response.get_data(as_text = True))

I'm building an app and I want to make some tests. I need to convert the response data from the test client to JSON.

The app:

tasks = [ { 'id': 1, 'title': u'Buy groceries', 'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', 'done': False }, { 'id': 2, 'title': u'Learn Python', 'description': u'Need to find a good Python tutorial on the web', 'done': False } ] app = Flask(__name__, static_url_path="") @app.route('/myapp/api/v1.0/tasks', methods=['GET']) def get_tasks(): return jsonify({'tasks': [task for task in tasks]}) if __name__ == '__main__': app.run(debug=True)

The tests:

class MyTestCase(unittest.TestCase): def setUp(self): myapp.app.config['TESTING'] = True self.app = myapp.app.test_client() def test_empty_url(self): response = self.app.get('/myapp/api/v1.0/tasks') resp = json.loads(response.data) print(resp) if __name__ == '__main__': unittest.main()

When I try to convert response.data to JSON, I get the following error:

TypeError: the JSON object must be str, not 'bytes'

How can I fix this error and get the JSON data?

解决方案

You need to get the response data as text, but the default is bytes. The response object provides the method get_data to control this.

data = json.loads(response.get_data(as_text=True))

更多推荐

将测试客户端数据转换为JSON

本文发布于:2023-07-27 05:26:13,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   客户端   测试   数据   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!