user6313136
user6313136

Reputation: 345

Changing the created JSON object key when rendering a json response

I'm rendering some json that outputs this

 render json: service.get_object_item(param)
[
    [0] "{"object_item":[{"count":1,"dueDate":"2021-02-23","dayCreated":23}]}"
]

I want to change the object_item array key to camel case so it will match the inner array casing.

[
    [0] "{"objectItem":[{"count":1,"dueDate":"2021-02-23","dayCreated":23}]}"
]

However it seems like it gets set when render gets called so I can't change it. I've only been able to omit it by doing render json: service.get_object_item(param).to_json.

Upvotes: 0

Views: 475

Answers (2)

user6313136
user6313136

Reputation: 345

I was able to solve it with this

render json: { objectItem: service.get_object_item(param) }

Which returns

[
    [0] "{"objectItem":[{"count":1,"dueDate":"2021-02-23","dayCreated":23}]}"
]

Upvotes: 1

V P
V P

Reputation: 1

You can either use active model serializers and define the keys there, or you can use rails built in transform_keys function

Upvotes: 0

Related Questions