All threads / How to serialize stored JSON serialization (in Ruby/Rails)?

Ask A Question

Notifications

You’re not receiving notifications from this thread.

How to serialize stored JSON serialization (in Ruby/Rails)?

zino asked in Ruby

I'd like to store a JSON blob in my table (Postgres). The table needs to be read frequently. After my application reads the table, it returns a JSON serialization of this blob along with other attributes of this table to the client.

# To illustrate, imagine an object like this
{
  name: 'foo',
  blob: {...} # this is blob that needs to be stored
}

and when a client requests for it, I'd like to return a JSON response like

{"name": "foo", "blob": [...]}

Given a Postgres database, the obvious choice is to store blob in a json/jsonb column. But what about a text column? Assuming blob is not used by the application, storing a serialized string in a text column means server doesn't need to deserialize the blob then serialize back to JSON whenever the client sends a request. In other words, the server can simply treat the blob as a string. Sounds more efficient, right?

However, because blob is now treated as a string, the serialization I get becomes

{"name": "foo", "blob": "[...]"} # note the extra " around the array brackets

This leads to incorrect parsing in the client application since now blob is parsed as a string instead of an array.

So my question is

a. Am I correct in assuming that a text column will be more efficient than jsonb (assuming this problem is solved)?

b. if so, whether there's a way to return an already serialized JSON object without treating it as a string? If not, what's the best way to avoid this type of deserialize-then-immediately-serialize waste?

Hey zino,

A text column should work just fine. Rails will escape strings by default, which is what it will think it is given it's a text column.

When you render it out, you'll need to make sure it's rendered as raw values instead of as a string.

Something like <%= @record.column.html_safe %> which would flag it as safe string to render directly without escaping.

The exact way you do that in your response will depend a bit upon which library you're using to render the JSON response, but that's the gist of it.

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 37,629+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.