panko_serializer icon indicating copy to clipboard operation
panko_serializer copied to clipboard

How to use a raw JSON string inside a serializer?

Open mnmallea opened this issue 3 years ago • 2 comments

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?

mnmallea avatar Feb 25 '21 19:02 mnmallea

@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.

yosiat avatar Sep 21 '21 20:09 yosiat

@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.

ElMassimo avatar May 24 '22 12:05 ElMassimo