python json object array not serializable
<p>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?</p>

<pre><code>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})
</code></pre>

<p>Does it say myclass object is not JSON serializable? This is because there is no way for <code>json.dumps(..)</code> to know how to JSON-serialize your class. You will need to write your <a href="https://docs.python.org/2/library/json.html#json.JSONEncoder" rel="nofollow">custom encoder to do that</a>.</p>

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

<pre><code>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}]
</code></pre>

<hr>

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

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

python json ajax serialization