I have string data that look like bytes reprs of JSON in Python
>>> data = """b'{"a": 1, "b": 2}\n'"""
So on the inside of that, we have valid JSON that looks like it's been byte-encoded. I want to decode the bytes and loads the JSON on the inside, but since its a string I cannot.
>>> data.decode() # nope
AttributeError: 'str' object has no attribute 'decode'
Encoding the string doesn't seem to help either:
>>> data.encode() # wrong
b'b\'{"a": 1, "b": 2}\n\''
There are oodles of string-to-bytes questions on stackoverflow, but for the life of me I cannot find anything about this particular issue. Does anyone know how this can be accomplished?
Things that I do not want to do and/or will not work:
evalthe data into a bytes object- strip the
band\n(inside of my JSON there's all sorts of other escaped data).
This is the only working solution I have found, and there is a lot not to like about it:
from ast import literal_eval
data = """b'{"a": 1, "b": 2}\n'"""
print(literal_eval(data[:-2] + data[-1:]).decode('utf-8'))
ast.literal_eval. There's probably a good dupe target somewhere around here.literal_evalattempt is almost certainly due to a bug you introduced while attempting to write a string literal fordata- you've got an actual newline in the middle of your bytes literal, which is invalid syntax for a bytes literal. You probably meant for that to be an actual backslash and n - that, or the newline was supposed to be outside the bytes literal.data = r"""b'{"a": 1, "b": 2}\n'"""is likely more representative of the actual kinds of values you're working with. If it's not, then that's going to be an issue.