Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
mnmallea opened this issue Feb 25, 2021 · 2 comments
Open

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

mnmallea opened this issue Feb 25, 2021 · 2 comments

Comments

@mnmallea
Copy link

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
Copy link
Owner

yosiat commented Sep 21, 2021

@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
Copy link

ElMassimo commented May 24, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants