I am hoping someone can help me understand this. I have a base64 string for an image:
"data:image/jpeg;base64,/9j/4AAQSkZJRgABA..."
I would like to send it using ember's createRecord and commit():
this.get('store').createRecord(Emb.Painting, {name: newName, image: newImage});
Then I want to convert it to StringIO for carrierwave and save it:
StringIO.class_eval { def original_filename; "stringiohaxx.jpg"; end }
io = StringIO.new(Base64.decode64(params[:painting][:image]))
#painting = Painting.create(:name => params[:painting][:name], :image => io )
An image is saved. The image is always corrupted. Do I need to break my break my base64 string into:
data: '/9j/..'
type: 'image/jpeg'
? Any help appreciated.
Yes, you need to split the string. You could use something like this:
def splitBase64(uri)
if uri.match(%r{^data:(.*?);(.*?),(.*)$})
return {
type: $1, # "image/png"
encoder: $2, # "base64"
data: $3, # data string
extension: $1.split('/')[1] # "png"
}
end
end
Then you can decode the image...
base64image = params[:painting][:image]
imageDataString = splitBase64(base64image)[:data]
imageDataBinary = Base64.decode64(imageDataString)
Then you can pass the imageDataBinary to StringIO.new() and the resulting image should be valid.
And yes that string does need to be broken up:
var data = newImage.split(',');
this.get('store').createRecord(Emb.Painting, {name: newName, image: data[1]});
I doubt this is the best way...
Related
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?
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
I am able to convert a YAML file to JSON, but I am not able to convert a YAML string to JSON. Is there any other way to convert YAML string to JSON?
Sample Input
---
:name:
:firstname: Guru
:lastname: Shyam
Expected output
{
"name": {
"firstname": "Guru",
"lastname": "Shyam"
}
}
Try Pysch.load
data = "---\n:name:\n :firstname: Guru\n :lastname: Shyam\n"
Psych.load(data)
-> {
:name => {
:firstname => "Guru",
:lastname=> "Shyam"
}
}
YAML.load_file might help you.
Btw, it is an alias for Psych but has a more convenient name, and included in ruby standart library.
[2] pry(main)> .cat data.yml
---
:name:
:firstname: Guru
:lastname: Shyam
[3] pry(main)> require 'yaml'
=> true
[4] pry(main)> puts YAML.load_file('data.yml').to_json
{"name":{"firstname":"Guru","lastname":"Shyam"}}
=> nil
I need to build a json object inside a loop using params.
My params look like this...
params[:answers]
returns => {"1"=>"answer1", "2"=>"answer2"}
The keys in this json object are the id's of the survey question.
So I planed to loop through the keys to build the json object like this...
def build_answersheet_json(params[:answers], params[:survey_id])
params[:answers].keys.each do |question_id|
current_question = question_id
current_answer = params[:answers][question_id]
end
end
Since im using "t.json" in my migration to save json to postgres, I wanted to use the extracted question_id and answer to build a json object that looks something like this...
{
survey_id: '1',
answers: {
question: [{
question_id: 1,
answer: 'answer1'
}, {
question_id: 2,
answer: 'answer2'
}]
}
}
Ive been trying to do this using a method that looks somthing like this...
build_answersheet_json(params[:answers], params[:survey_id])
Ive tried JSON.parse() and Ive tried to just logically work through it but I cant seem to figure this out.
Any help is appreciated.
Maybe you can try something like that:
/* fake params (to test) */
params = {
survey_id: '1',
answers: {
"1"=>"answer1",
"2"=>"answer2",
"3"=>"answer3",
"4"=>"answer4"
}
}
def build_answersheet_json(answers, survey_id)
{
survey_id: survey_id,
answers: answers.map { |k,v| { question_id: k.to_i, answer: v } }
}
end
survey = build_answersheet_json(params[:answers], params[:survey_id])
puts survey.class
#Hash
puts survey.to_json
# formated JSON string:
# {
# "survey_id":"1",
# "answers":[
# {"question_id":1,"answer":"answer1"},
# {"question_id":2,"answer":"answer2"},
# {"question_id":3,"answer":"answer3"},
# {"question_id":4,"answer":"answer4"}
# ]
# }
In order to save to a t.json postgress column type, just pass the Hash survey object, like that:
YourModel.create(survey: survey)
Source: http://edgeguides.rubyonrails.org/active_record_postgresql.html
Try
{
survey: ¯\_༼◉ل͟◉༽_/¯,
}
Json may not be parsed if json have construction like this:
survey = {
}
Json may not contain = and assignment
Check real variables values with puts varname.inspect near at code lines where you meet unexpected behaviour.
Whats the right approach to write number of hashesh to a json file that can be parsed effeciently later on.
e.g:
hash1 = {:a=>1,:b=>'foo'}
hash2 = {:c=>3,:b=>'bar'}
...
hashN = {...}
File.open("data.json", "a") { |io| io.write(hash1.to_json)}
I can write a comma after each hash to the file, but this is not looking nice to me.. is it a better way to do it?
that can be parsed effeciently later on.
You will want to put your hashes in a list so that later you can load and parse everything in one sweep:
require 'json'
arr = []
arr << {:a=>1,:b=>'foo'}
arr << {:c=>3,:b=>'bar'}
json_str = arr.to_json
File.open("yourfile", 'w') { |file| file.write(json_str) }
Later on to load:
contents = File.read('yourfile')
arr = JSON.parse(contents)
Hi I have a JSON string that looks like this (Usingt Rails and a REST service)
{
person:
{
name:"Pepe",
last:"Smith"
hats:[ { team:"lakers", color:"purple"}, { team:"heats", color:"red" }] } }
I want to be able to able to get that JSON, and save the Person to the database, but I want to save the "hats".. as a string to the database; without parsing it or anything like that
i.e. I want to save this to SQL:
hats = "[ { team:"lakers", color:"purple"}, { team:"heats", color:"red" }] }"
Is there a way to do this in rails?
The JSON string gets converted to params hash before a controller action is invoked.
You could make to_json call on the hats attribute to get an equivalent json string.
def create
params[:person][:hats] = (params[:person][:hats]||{}).to_json
p = Person.new(params[:person])
if p.save
#success
else
#error
end
end