sysid / sse-starlette

BSD 3-Clause "New" or "Revised" License
505 stars 36 forks source link

JSON objects are sent using single quotes causing JSON parsing failure on browser side #21

Closed deepio-oc closed 2 years ago

deepio-oc commented 2 years ago

I am trying to send a dictionary object to the browser but JSON.parse fails on browser side saying single quotes are not allowed.

The issue is with the following code, which tries to convert dictionary to string (resulting in single quotes).

        for chunk in self.LINE_SEP_EXPR.split(str(self.data)):
            buffer.write(f"data: {chunk}")
            buffer.write(self._sep)

Could you check the data type and may use json.dumps or provide it as configuration option?

sysid commented 2 years ago

Hi deepio-oc, sorry for the late reply, I have been on summer leave. I am not sure whether I understand your issue properly. What you pass in as data is in your responsibility, so I would assume you need to take care of proper serialisation. If I am missing something, please reopen.

deepio-oc commented 2 years ago

if self.data is dictionary object, str(self.data) does not generate a compliant json string. It is converting to string using single quotes for the key and values (e.g "{'key':'value'}"). JSON.parse in the browser can not load this string back to dictionary object.

pavlo-yashchuk commented 2 years ago

Yes, deepio-oc right When I transfer json data, in ServerSentEvent.encode the dictionary turns into a string, but I want to transfer json file :(

deepio-oc commented 2 years ago

@pavlo-yashchuk dictionary need to be encoded as string before it is sent. On the receiver side, you need to decode it back to json object from string.

my issue is that encoded string format is not JSON compliant and I cant decode it back.

@sysid I dont see any option to open this ticket.

pavlo-yashchuk commented 2 years ago

Okay) but I found solution for me add json loads before dumps image

CiberNin commented 1 year ago

I don't think this should be marked closed. Converting dicts to valid JSON seems like a reasonable task for the library to handle, and not a particularly hard feature to add. For example, right now simple code like this won't work. image

m-roberts commented 9 months ago

I agree that converting a dict to valid JSON is something I would expect the library to take care of. I've added a PR to address this here: #79