i just create a migration like this
def change
add_column :articles, : information, :json,
default: '[{ "type:c":"12", "temperature":12 }]', null: false
end
i just migrated that table
right now, to create a new article, i am sending this in my request with postman, i am sending properly the 'information' as string?
{
"section":"139",
"information":"[{ type:c, temperature:9 }]" //string
}
so far every thing is ok
now i want to get the param information as a array not string
I want to convert information in an array of json object, how can i do that?
CodePudding user response:
This can be achieved in two ways.
require 'yaml'
input_params = {"section":"139","information":"[{ type: c, temperature: 9 }]"}
#=> {"section"=>"139", "information"=>"[{ type: c, temperature: 9 }]"}
YAML.load(input_params['information'])
#=> [{"type"=>"c", "temperature"=>9}]
or If you want to use JSON.parse
then input_params
should be as below:
require 'json'
input_params = {"section"=> "139", "information" =>'[{ "type":"c", "temperature":"9" }]'}
#=> {"section"=>"139", "information"=>"[{ \"type\":\"c\", \"temperature\":\"9\" }]"}
JSON.parse(input_params['information'])
#=> [{"type"=>"c", "temperature"=>9}]
I hope this will help you