1

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})
6
  • what is mng01 can you give an example. Commented Oct 3, 2016 at 9:13
  • Can you post the error stack please ? When I try to dump {'success':'1','vehicle':vehicle_sum} with vehicle_sum being a standard python array, it works. Please provide more details regarding the error and the objects you use :) Commented Oct 3, 2016 at 9:15
  • 1
    @FloranGmehlin: It is a list, of instances of myclass. This will not work out of the box. See my answer below :) Commented Oct 3, 2016 at 9:19
  • I see, did not think about that :) Thx ! Commented Oct 3, 2016 at 9:22
  • Why do you have two self.vehicle = vehicle statements in myclass.__init__()? Commented Oct 3, 2016 at 9:47

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I get An attribute defined in json.encoder line 162 hides this method , it happens on the line def default(self, obj): but the code still works.
0

It doesn't say that JSON is not serializable, it says that your instances of myclass are not JSON serializable. I.e. 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.