如何正确地从数据存储中保存和获取JSON? [英] How to properly save and fetch JSON from Datastore?

查看:46
本文介绍了如何正确地从数据存储中保存和获取JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google App Engine和Python.

I'm using Google App Engine and Python.

class Spam(db.Model)
  eggs = db.TextProperty

# Create some json and store it to a Spam Entity
eggs_dict = {"large":10, "medium":5, "small":24}
eggs_json = simplejson.dumps(eggs)
spam = Spam(eggs=db.Text(eggs_json))

# Later, fetch spam and then return the json as part of a Response
self.response.out.write(spam.eggs)

执行此操作时,我会收到如下响应:

When I do this I get a Response that looks like:

{"large":"10","medium":"5","small":"24"}

这是我第一次使用JSON + Python + GAE数据存储,我的问题是这似乎是存储和获取JSON字符串的正确方法,但是在我将此设计模式提交给其他实体之前,我想看看这是否是一个好的模式,并且以后不会出现任何数据错误.具体来说,我是否需要在进出数据存储区的过程中执行任何编码?

This is my first time working with JSON + Python + GAE Datastore, and my question is that this seems to be the proper way of storing and fetching JSON Strings, but before I commit this design patter to other Entities, I wanted to see if this is a good pattern and not prone to any data errors down the road. Specifically do I need to perform any encoding on the way in or out of the Datastore?

推荐答案

在AppEngine数据存储区中插入字符串"(您已将字典序列化为字符串)后,您无需进行任何编码.

You shouldn't need to do any encoding when inserting a 'string' (you've serialized your dictionary to a string) into the AppEngine datastore.

我尝试了以下代码,并从数据存储区中检索到了完全相同的字符串.

I tried the following code and got back the same exact same string when retrieved from the datastore.

eggs_dict = {"large":10, "medium":5, "small":24}
eggs_json = simplejson.dumps(eggs_dict)
spam = Spam(key_name='blah')
spam.eggs = eggs_dict
db.put(spam.eggs)        

new_spam = db.get(db.Key.from_path('Spam', 'blah'))

# Later, fetch spam and then return the json as part of a Response
self.response.out.write(new_spam.eggs)

这篇关于如何正确地从数据存储中保存和获取JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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