Cloud Confusing

Explaining hosting, AWS, Wordpress, static sites, and all manner of cloud solutions.

If you are working with JSON in Python, then you might run into a common problem. You’ll know you have a problem because when running your Python you’ll get an output error that reads, “the JSON object must be str, bytes or bytearray, not list.” In common Python fashion, the message actually makes some sense but you’re still left trying to figure out what to do next.

How You Got Here

The good news is that if you are seeing this error, the fix is normally quite simple.

In all likelihood you are working with something that looks like a JSON array in your Python script and you’ve decided that you’d like to iterate through it, or work with it in some similar way.

Your next line might be something like:

loaded = json.loads(topics)

Where you want to get that JSON-like array and handle it as a true JSON array since you’ve finally remembered to import the JSON module. This is when you’ll get the “The JSON object must be str, bytes or bytearray, not list” error. Sounds familiar?

How To Fix The Error

If you want a quick fix for the error, don’t use json.loads. Instead try json.dumps. This simple swap will likely fix your problem.

It’s an easy change that has helped me many times… especially since json.loads is always the one I see to want to try first as it seems semantically logical in this scenario.

What Just Happened?

Long story short, what you were working with looked like JSON, but it wasn’t being considered as being JSON by Python.

json.loads get a valid (properly formatted) JSON string and makes it a usable Python dictionary.

json.dump sort of does the opposite — it gets a serialized object and makes it JSON-formatted data.

You’ll see this happen as json.dump does some cool things, like turn a single-quote-laden Python dictionary and move over to a valid double quote formatted JSON array.

So if you have good JSON and you need to read it, use json.loads. If you have a Python string and want it to be json, use json.dumps.

And then, most importantly, don’t confuse these two with the json.load and json.dump methods. They sound a lot alike, but they have very different uses!

October 24th, 2022

Posted In: Python


© Cloudconfusing.com 2022 | Privacy Policy | About | UTM Creator | CVE Reporting