Question

I am currently attempting to push html updates to a page for a user using PubNub. I want to push html code to the user (this includes links, quotes, making html necessary), and add it to the end of a table for the user.

I am currently attempting to use the api to send a message as follows:

info = pubnub.publish({
        'channel' : 'myChannel',
        'message' : {
        'some_text' : message
        }
    })

Where message is:

<div class="content">Message text here.<img src="image.gif" border="0" alt="" title="laugh out loud" class="inlineimg" /></div>

My issue is that I am receiving the following message when I attempt to send a page update:

</div> is not JSON serializable

I am assuming this is occurring because I am attempting to send html code?

Any recommendations on how to fix this / better ways to do this? This is my first attempt at "pushing" messages to a webpage, so I may be implementing this all wrong.

Was it helpful?

Solution

You are attempting to send raw HTML via PubNub and running into the "JSON not Serializable" issue. Firstly, you are correct in assuming that you Can push HTML code! Hurray. Just make sure that the data you place inside the "message" is in fact a STRING. The following types are JSON Serializable:

  1. Objects
  2. Arrays
  3. Strings
  4. Numbers

Make sure to not send special python classes or functions. These will not serialize. String content can include any UTF-8 character single-byte and multi-byte.

Use this Python for the "message":

message = '''<div class="content">Message text here.<img src="image.gif" border="0" alt="" title="laugh out loud" class="inlineimg" /></div>'''

OTHER TIPS

I am no web expert but to me sounds like you should define a model and send that instead. You then would deserialize the model and update the client. That way you can use JSon and you won't run into any issues.

If you absolutely have to send the HTML, Another option when transferring HTML is to encode it in a base 64 string. With this approach you would have encode the string prior to sending it and decoding it on the receiving client. There is plenty of information on encoding base64 strings on google. This keeps the string from tripping up on HTML tags and such.

Here is an example of what encoding to and from base64 looks like: http://ostermiller.org/calc/encode.html For example the following code:

<img src="images/mypicture.jpg"></img>
<div id="chat-box"/>
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

Would look like this as a base64 string

PGltZyBzcmM9ImltYWdlcy9teXBpY3R1cmUuanBnIj48L2ltZz4KPGRpdiBpZD0iY2hhdC1ib3gi

Lz4KPHVsPgogIDxsaT5JdGVtIDE8L2xpPgogIDxsaT5JdGVtIDI8L2xpPgo8L3VsPg==

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top