json - 摆脱 JSON 中的 Mongo $ 符号

标签 json mongodb flask python-3.4 flask-mongoengine

我正在使用 MongoDB 为 SPA (Angular) 构建 python 后端。

这是我使用的:Python 3.4MongoDB 3Flaskflask-mongoengineflask-restful

现在我从后端收到以下 JSON:

[
    {
        "_id": {
            "$oid": "55c737029380f82fbf52eec3"
        },
        "created_at": {
            "$date": 1439129906376
        },
        "desc": "Description.....",
        "title": "This is title"
    },
    etc...
]

我想收到类似的东西:

[
    {
        "_id": "55c737029380f82fbf52eec3",
        "created_at": 1439129906376,
        "desc": "Description.....",
        "title": "This is title"
    },
    etc...
]

我现在的代码:

from flask import json
from vinnie import app
from flask_restful import Resource, Api
from vinnie.models.movie import Movie

api = Api(app)

class Movies(Resource):
    def get(self):
        movies = json.loads(Movie.objects().all().to_json())
        return movies

api.add_resource(Movies, '/movies')

型号:

import datetime
from vinnie import db

class Movie(db.Document):
    created_at = db.DateTimeField(default=datetime.datetime.now, required=True)
    title = db.StringField(max_length=255, required=True)
    desc = db.StringField(required=True)

    def __unicode__(self):
        return self.title

为前端格式化方便的 JSON 的最佳方式是什么?

最佳答案

如果您有信心摆脱所有类似情况,那么您当然可以编写与该模式匹配的代码。例如:

info = [
    {
        "_id": {
            "$oid": "55c737029380f82fbf52eec3"
        },
        "created_at": {
            "$date": 1439129906376
        },
        "desc": "Description.....",
        "title": "This is title"
    },
    #etc...
]

def fix_array(info):
    ''' Change out dict items in the following case:
           - dict value is another dict
           - the sub-dictionary only has one entry
           - the key in the subdictionary starts with '$'
        In this specific case, one level of indirection
        is removed, and the dict value is replaced with
        the sub-dict value.
    '''
    for item in info:
        for key, value in item.items():
            if not isinstance(value, dict) or len(value) != 1:
                continue
            (subkey, subvalue), = value.items()
            if not subkey.startswith('$'):
                continue
            item[key] = subvalue

fix_array(info)
print(info)

这将返回:

[{'title': 'This is title', 'created_at': 1439129906376, 'desc': 'Description.....', '_id': '55c737029380f82fbf52eec3'}]

显然,用 JSON 重新格式化是微不足道的。

关于json - 摆脱 JSON 中的 Mongo $ 符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31904012/

相关文章:

Python - 使用 gevent 时出现 NameError : name 'PROTOCOL_SSLv3' is not defined,

javascript - 如何用javascript浏览json内容?

java - 解析 json 对象并附加到 recyclerview

mongodb - 通过 MongoDB Compass 社区连接到 EC2

scala - 使用 Casbah 通过正则表达式查找

python - Flask-SQLAlchemy 缺少 "caching_sha2_password"身份验证模块

python - 重启 Wsgi 服务器时重启 ApScheduler Python 中的作业

php - 输出数据到表中

java - ERROR 411 在 java 中使用 API(POST 方法)

javascript - 书籍及其图像未呈现在页面上