My goal is to write the response I get from a call to Amazon's Product Advertising API to a file in JSON format.
I call the API using
response = default_api.search_items(search_items_request)
I attempt to write the results to a file using:
with open('data.json', 'w') as f:
json.dump(response, f)
I get the error message:
TypeError : Object of type 'SearchItemsResponse' is not JSON serializable
How can I fix this? I need to write the response in JSON. A solution is greatly appreciated.
json only knows about standard data types -- int, float, list, string, dictionary, etc.
If you want to save an arbitrary class object with json, you'll have to write a custom dump routine that decomposes the object into those basic types, and a custom load routine that reads those basic types and reconstructs the object.
If you're able, it might be a lot easier to use pickle instead, which does support saving arbitrary class objects.