yosiat / panko_serializer

High Performance JSON Serialization for ActiveRecord & Ruby Objects
https://panko.dev
MIT License
592 stars 36 forks source link

How to use a raw JSON string inside a serializer? #95

Open mnmallea opened 3 years ago

mnmallea commented 3 years ago

Hi I have seen this example on Panko docs:

  posts = Cache.get("/posts")

   render json: Panko::Response.new(
     success: true,
     total_count: posts.count,
     posts: Panko::JsonValue.from(posts)
   )

But I currently need to use JsonValue on an attribute inside a serializer. Like this:

class PostSerializer < Panko::Serializer
  attributes :id, :text ## other attributes
  attributes :some_raw_json_array

  def some_raw_json_array
     Panko::JsonValue.from('[{ "a": 1}, {"a": 2}]')
  end
end

But, when I call PostSerializer.new.serialize_to_json(OpenStruct.new(id: '1', text: 'foo')) I get this JSON:

{"id":"1","text":"foo","some_raw_json_array":{"value":"[{ \"a\": 1}, {\"a\": 2}]"}}

instead of getting:

{"id":"1","text":"foo","some_raw_json_array": [{ "a": 1}, {"a": 2}]}

Is this behaviour right? Is there any way to obtain my desired ouput?

yosiat commented 3 years ago

@mnmallea currently it's not possible to return raw JSON from methods, the only thing panko does in this area is for attributes, if you have JSON column in your DB and you serialize that - Panko will optimize this case.

I'll try to give it a check and see how can I support that efficiently, if you want to try and check this - I can help and guide you submitting PR.

ElMassimo commented 2 years ago

@yosiat It's possible to support this by using the raw_json API in oj.

This enables intuitive usage without a wrapper like Panko::Response, and would solve this issue as well as https://github.com/panko-serializer/panko_serializer/issues/105.

Let me know if you'd be interested in combining some of the ideas in oj_serializers into Panko, this library was a great inspiration, and I love the approach you took of bypassing ActiveRecord and performing the coercion in C.