Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a hash or json string into a jsonb field

I have a json string from my active admin from "{\"en\":\"Lorem\"}"

I want to save this in my question.name field, which is of postgres jsonb type.

class Question < ActiveRecord::Base
  serialize :name
end

# db/schema.rb
create_table "preset_questions", force: :cascade do |t|
  t.jsonb    "name",               default: {}
end

I've tried the following:

question.update(name:"{\"en\":\"Lorem\"}")
question.update(name:JSON.parse("{\"en\":\"Lorem\"}"))

Result for both:

question.name
=> nil
like image 295
Martin Verdejo Avatar asked Feb 12 '16 10:02

Martin Verdejo


People also ask

Can we store JSON in string in PostgreSQL?

PostgreSQL offers two types for storing JSON data: json and jsonb . To implement efficient query mechanisms for these data types, PostgreSQL also provides the jsonpath data type described in Section 8.14. 7. The json and jsonb data types accept almost identical sets of values as input.

What is difference between JSON and Jsonb?

One simple difference between JSON and jsonb data type is that JSON stores the exact copy of the data represented/ inputted in the JSON format to the user whereas jsonb stores the data in the binary format which means that the input data is first processed and then stored in the binary form.

Is Jsonb faster than JSON?

Because JSONB stores data in a binary format, queries process significantly faster. Storing data in binary form allows Postgres to access a particular JSON key-value pair without reading the entire JSON record.

What is Jsonb []?

JSON-B is a standard binding layer for converting Java objects to/from JSON messages. It defines a default mapping algorithm for converting existing Java classes to JSON, while enabling developers to customize the mapping process through the use of Java annotations.


1 Answers

Got it to work by removing serialize :name. Looks like rails already knows what to do given that the column type is jsonb

class Question < ActiveRecord::Base
end

# db/schema.rb
create_table "preset_questions", force: :cascade do |t|
  t.jsonb    "name",               default: {} 
end

question.update(name:"{\"en\":\"Lorem\"}")
question.update(name:JSON.parse("{\"en\":\"Lorem\"}"))

Both return

question.name
=> {"en"=>"lorem", "id"=>"ipsum"}
like image 186
Martin Verdejo Avatar answered Sep 20 '22 00:09

Martin Verdejo