简体   繁体   中英

python json object array not serializable

I have a class and array in a loop. I'm filling the object and appending it to the array. How do I pass array data to web side through JSON? I have an error that says JSON is not serializable. How can I serialize to a JSON?

class myclass(object):
    def __init__(self,vehicle,mng01):
        self.vehicle = vehicle
        self.vehicle = vehicle

#--Main function--
@subApp.route('/jsontry', method=['POST'])
def data():
    for x in list:
        vehicle_sum.append(myclass( x,str(mng01))

    return json.dumps({'success':'1','vehicle':vehicle_sum})

Does it say myclass object is not JSON serializable? This is because there is no way for json.dumps(..) to know how to JSON-serialize your class. You will need to write your custom encoder to do that .

Below is a sample implementation. I am sure you can modify it for your use case.

import json

class Temp(object):
    def __init__(self, num):
        self.num = num

class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Temp):
            return {"num": obj.num}
        #Let the base class handle the problem.
        return json.JSONEncoder.default(self, obj)

obj = [Temp(42), Temp(42)]


print json.dumps(obj, cls=CustomEncoder)

#Output: [{"num": 42}, {"num": 42}]

If you don't want over-complicate stuff, here's what you can do:

all_vehicles = [{"vehicle": x.vehicle} for x in vehicle_sum]
json.dumps({'success':'1','vehicle':all_vehicles)

It doesn't say that JSON is not serializable, it says that your instances of myclass are not JSON serializable. Ie they cannot be represented as JSON, because it is really not clear what do you expect as an output.

To find out how to make a class JSON serializable, check this question: How to make a class JSON serializable

In this trivial case, depending on what exactly you're trying to achieve, you might be good with inserting [x.vehicle for x in vehicle_sum] in your JSON. If you really need to insert your instances data in JSON in a direct way, you'll have to write an encoder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM