Hacker News new | past | comments | ask | show | jobs | submit login

> That's also an example where trying to model the strict reality (having no known name) might be worse than just using a workaround in a simpler model.

A bit of an orthogonal example to the thread, but I ran into an issue like that, with a solution that worked just like you described. I was using msgpack in Python 3 to send data to the browser in JSON format.

msgpack in Python 3 decodes into bytes, as (hopefully) expected by Python 3 users.

Except the data was somewhat arbitrary in terms of how it was organized or what was included (but was predictable in type), so decoding it was a bit of a pain. The problem of course was that my strings were wrapped in b'', and that was being sent to the browser, causing the JSON parsing in the browser to fail.

My first two attempts were recursive algorithms that would try and decode strings and skip everything else (we only worked with strings and numbers, or lists of strings and numbers, hence "predictable in type"). Both times it almost worked, but didn't. Even with predictable types of data, I had to try and cover a number of edge cases.

The solution that ended up working 100% of the time in my particular case was just using regex to remove the occurrences of b'' from a string version the object, then send that as JSON. Looked like an ugly hack, and probably was, but it damn sure worked like a charm. It was much easier to just ensure I built a valid dictionary before encoding it with msgpack rather than try and "properly" decode all the strings after decoding it with msgpack.




You could subclass the json.JSONEncoder class (and implement the default method) to decode bytes objects, along the lines of the example in the documentation:

https://docs.python.org/3.5/library/json.html




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: