Invalid JSON: trailing characters

Try to subscribe to btcusdt@bookTicker on wss://data-stream.binance.vision:443.

Send request
{“method”:“SUBSCRIBE”,“params”:[“btcusdt@bookTicker”],“id”:1} and receive response
{“error”:{“code”:3,“msg”:“Invalid JSON: trailing characters at line 1 column 62”}}

libwebsockets write on screen before send request

What wrong I do?

Hi @achuprynov,

Your payload looks valid and the book ticker should work for BTCUSDT pair.

Could you please ensure that your request does not contain any extra bytes, such as NULL (0x00), newlines, or other unexpected characters at the end? Try to format and log the JSON before sending it to ensure that structure is correct.

Also ensure that your data is encoded as UTF-8 before sending it.

Let us know if that helps!

Hi, @dimitrisn

Thanks for advise. I checked request and it does not contain any extra bytes. On screen above hex dump of byte array before send. (Last 2 byte 0x00 0x00 on screen not sending) There all bytes valid.
Empty bytes before request for header.

image
This is code of sending request by libwebsockets v4.2.0

The same code working fine on OKX. How Binance parsing JSON that valid request became invalid …

I have not more time and ideas for research this problem. I will using request in URL (“/stream?streams=btcusdt@bookTicker/ethusdt@bookTicker”)

Hi @achuprynov.

Since Binance is still rejecting the request, here are a few more things to check:

1. Confirm LWS_PRE Usage

  • In lws_write(), you’re passing request + LWS_PRE. This means there’s a reserved buffer space before the actual request.
  • Ensure that the offset is being handled correctly and doesn’t introduce any unintended data before the JSON payload.

2. Verify WebSocket Frame Formatting

  • Binance might be stricter about WebSocket frame structure. Try logging the full raw WebSocket frame being sent.
  • Use lws_hexdump_notice() before sending to inspect what’s actually going out.

3. Try Sending Without Pre-allocated Buffer (LWS_PRE)

  • If LWS_PRE isn’t required for this request, try sending without it:
long unsigned int sentBytes = lws_write(
    wsi,
    request,  // No offset
    length,
    (enum lws_write_protocol)flags
);

Let us know if this helps!