50 Experience
0 Lessons Completed
0 Questions Solved


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?

logo Created with Sketch.

Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

© 2022 GoRails, LLC. All rights reserved.