12

So I have some python dict that I want to serialize to JSON

{'someproperty': 0, 'anotherproperty': 'value', 'propertyobject': SomeObject(someproperty=0, anotherproperty=0)} 

but json.dumps throws a TypeError: SomeObject(someproperty=0, anotherproperty=0) is not JSON serializable

So how can I serialize my python dict properly?

1
  • You cannot have object even SomeObject should be a json object. something like {'someproperty': 0, 'anotherproperty': 'value', 'SomeJson':{'someproperty':0, 'anotherproperty':0}} Commented Apr 27, 2016 at 4:08

2 Answers 2

17

The problem is, python doesn't know how to represent SomeObject

You can create a fallback like so:

import json def dumper(obj): try: return obj.toJSON() except: return obj.__dict__ obj = {'someproperty': 0, 'anotherproperty': 'value', 'propertyobject': SomeObject(someproperty=0, anotherproperty=0)} print json.dumps(obj, default=dumper, indent=2) 
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way I can return json data sorted by dictionary key?
@iDev yup, use sort_keys=True in json.dump
5

Python can serialize only the objects that is a built in data type. In your case, "SomeObject" is a User defined type that Python cannot serialize. If you try to serialize any data type which is not json serializable, you get a TypeError "TypeError: is not JSON serializable". So there should be an intermediate step that converts these non built in data types into Python built in serializable data structure (list, dict, number and string).

So let us convert your SomeObject into a python dictionary, since dictionary is the easiest way to represent your Object(as it has key/value pairs). You could just copy all your SomeObject instance attributes to a new dictionary and you are set! myDict = self.__dict__.copy() This myDict can now be the value of your "propertyobject".

After this step is when you convert dictionary to a string (JSON format, but it can be YAML, XML, CSV...) - for us it will be jsonObj = JSON.dumps(finalDict)

Last step is to write jsonObj string to a file on disk!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.