c0deNinja
c0deNinja

Reputation: 3986

How can I replace keys in to_json?

I am overriding to_json.

When I call to_json on my model I get the following:

{ "integer1": "23", "integer2": "2", "integer3": "4", ... }

I want to_json to return:

{ "Something": "23", "SomethingElse": "2", "AnotherThing": "4", ... }

I have an array that contains the key and its mapping:

"integer1" => "Something", "integer2" => "SomethingElse", "integer3" => "AnotherThing", ....

How can I achieve this?

Upvotes: 1

Views: 2432

Answers (2)

Chris Heald
Chris Heald

Reputation: 62708

I highly advocate using draper or a similar decorator-pattern solution to create "JSON views" of objects.

You would have a decorator for your model, on which you define def as_json(options = {}) and return a hash of the data you want to use as the JSON representation of your model. This decouples it from the model, and lets you modify the "data view" of the model separately from the internal representation of the data easily.

Upvotes: 3

Phrogz
Phrogz

Reputation: 303549

  1. Convert your model instance into a hash
  2. Convert the hash into what you want:

    h1 = { "integer1" => "23", "integer2" => "2", "integer3" => "4" }
    h2 = { "integer1" => "Something", "integer2" => "SomethingElse", "integer3" => "AnotherThing" }
    desired = Hash[ h1.map{ |k,v| [ h2[k], v ] } ]
    
  3. Get your JSON from that:

    json = desired.to_json
    

Upvotes: 4

Related Questions