0

I have a post model and controller. However when I upload image, it saves image_data as hash

{
        "id": 54,
        "image_data": "{\"id\":\"461dd0ca2c6ad31995a30039192d43cb.png\",\"storage\":\"store\",\"metadata\":{\"filename\":\"Artboard .png\",\"size\":13081,\"mime_type\":\"image/png\"}}",
        "user_id": 55,
        "created_at": "2017-10-31T06:42:35.809Z",
        "updated_at": "2017-10-31T06:42:35.908Z"
    } 

but I need it to be displayed as json string. to_json doesn't work, however, create controller works and shows perfectly when I do

def as_json(options={})
{
:image => self.image
}
end

But show, index, etc. give me an error <JSON::ParserError: 743: unexpected token at 'boo'

How can I make it work for everything to be displayed as json string?

{
    "image": {
        "id": "64b6f1b9654dc0ea91965e2003f7d270.png",
        "storage": "store",
        "metadata": {
            "filename": "Artboard .png",
            "size": 13081,
            "mime_type": "image/png"
        }
    }
}
  • It is already stores as string. To store JSON you need to use https://apidock.com/rails/ActiveRecord/Base/serialize/class or change column in the DB to type JSON(if you can) – kolas Oct 31 '17 at 09:44

1 Answers1

0

I think your question is how can you deeply convert this to JSON object, I don't think there is a built-in function that would do this, Take a look on this answer, So i think you should create a function that deeply convert it to JSON, Hope it would help.

Amr Adel
  • 574
  • 1
  • 7
  • 18