如何编码烧瓶中的json对象列表?

时间:2018-02-12 01:55:30

标签: python json flask

我已经编写了我的自定义jsonencoder,如下所示;

from flask.json import JSONEncoder

from models.AtgSiteToPoll import *


class CustomJSONEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, AtgSiteToPoll):
            return obj.__dict__


        return JSONEncoder.default(self, obj)

在我的主应用程序中,我将编码器设置如下;并尝试从数据库返回对象列表。对于单个对象,我将编码器称为jsonEncoder.default(a)但是如何将编码器用于对象列表(即:formatted_atgsites)?

from flask import Flask, jsonify, request
import httplib

app = Flask(__name__)
app.json_encoder = CustomJSONEncoder

def BuildATGSite(siteid):
    jsonEncoder = CustomJSONEncoder()
    atgsites=[]
    if siteid is None :
        atgsites = atgsitetopoll.query.all()
    else :
        atgsites = atgsitetopoll.query.filter_by(siteid=siteid).first()

    formatted_atgsites=[]
    a = AtgSiteToPoll()
    if atgsites !=[] :
        for atgs in atgsites:
            formatted_atgsites.append({
                a.SiteId = atgs.siteid
                a.IPAddress = atgs.ipaddress
                a.Port = atgs.port
                a.Category = atgs.category
                a.UserId = atgs.userid
                a.Password = atgs.password
                a.ReceiveTimeoutInMilliSeconds = atgs.receivetimeoutinmilliseconds })
    else:
        a.SiteId = '12345'
        a.IPAddress = '10.10.10.10'
        a.Port = 10001
        a.Category = 1
        a.UserId = 'testuser'
        a.Password = 'testpassword'
        a.ReceiveTimeoutInMilliSeconds = '60'

    return jsonEncoder.default(a)

2 个答案:

答案 0 :(得分:0)

iirc CustomJSONEncoder反复编码,但是因为你正在调用JSONEncoder.default(self, obj),所以它不会被递归调用。也许试试

class CustomJSONEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, AtgSiteToPoll):
            return obj.__dict__

        return obj

答案 1 :(得分:0)

这是一个例子(没有Flask)。

import json

# example of a custom class
class AtgSiteToPoll(object):

    def __init__(self, site_id, ip):
        self.site_id = site_id
        self.ip = ip
        # other properties ...

    def to_json(self):
        return {
            'SiteId': self.site_id,
            'IPAddress': self.ip,
            # other properties/structures etc...
        }


class CustomEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, AtgSiteToPoll):
            # get our dict
            return obj.to_json()
        # call default encoder(in this case we will process list)
        return json.JSONEncoder.default(self, obj)

example_list = [
    AtgSiteToPoll('1', '10.10.10.10'),
    AtgSiteToPoll('2', '10.10.10.11'),
    # other instances...
]

print(json.dumps(example_list, cls=CustomEncoder))
# output:
# [{"IPAddress": "10.10.10.10", "SiteId": "1"}, {"IPAddress": "10.10.10.11", "SiteId": "2"}]

希望这会有所帮助。我不建议您使用obj.__dict__(在所有情况下都不起作用)。