Python

Python: Object of type X is not JSON serializable

Aka how to sending Arrays of Class Objects through GET requests.

The catch with GET is, of course, that you can’t under normal conditions send your request with a body of JSON objects.

The answer is: convert those objects to strings or dicts first.

import json
import requests

# for a simple approach, convert the object to string with json.dumps
# or better yet, depending on which props you need, make a dict
tasks = [{cherry_pick_props_here} for t in tasks]

# the separator ensures that no useless white space hogs the string
tasks_str = json.dumps(tasks, separators=(",", ":"))

requests.get(url, params={"tasks": tasks_str})

At the other end, if it’s JavaScript parsing this URL, this would convert the array back into array:

JSON.parse(decodeURIComponent(tasks_str))

Standard

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.