1

I have a bytes object bytes_start containing a string of a list and I want to turn it into a Python object.

bytes_start = b'"[{\\"method\\": \\"NULLABLE\\", \\"title\\": \\"Customer\\", \\"type\\": \\"STRING\\"}, {\\"method\\": \\"NULLABLE\\", \\"title\\": \\"Vendor\\", \\"type\\": \\"INTEGER\\"}]"'

I tried using new_bytes_start = json.dumps(bytes_start), but that did not work. How can I use Python 3 to get the following result?

new_bytes_start = [{"method": "NULLABLE", "title": "Customer", "type": "INTEGER"}, {"method": "NULLABLE", "title": "Vendor", "type": "FLOAT"}]
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
bluetree8173
  • 59
  • 2
  • 5

1 Answers1

5

Your bytes value contains a double-encoded JSON document. You don't need to encode this a third time.

If you wanted to load the data into a Python object, you need to decode the JSON, twice, using json.loads():

import json

new_bytes_start = json.loads(json.loads(bytes_start))

Demo:

>>> import json
>>> bytes_start = b'"[{\\"method\\": \\"NULLABLE\\", \\"title\\": \\"Customer\\", \\"type\\": \\"STRING\\"}, {\\"method\\": \\"NULLABLE\\", \\"title\\": \\"Vendor\\", \\"type\\": \\"INTEGER\\"}]"'
>>> json.loads(bytes_start)
'[{"method": "NULLABLE", "title": "Customer", "type": "STRING"}, {"method": "NULLABLE", "title": "Vendor", "type": "INTEGER"}]'
>>> json.loads(json.loads(bytes_start))
[{'method': 'NULLABLE', 'title': 'Customer', 'type': 'STRING'}, {'method': 'NULLABLE', 'title': 'Vendor', 'type': 'INTEGER'}]

If you are using a Python version older than Python 3.6, you'll also have to decode the bytestring first; presumably it's UTF-8 at which point you'd use:

new_bytes_start = json.loads(json.loads(bytes_start.decode('utf8')))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343