When attempting to send a JSON object from JavaScript to Ruby, I am encountering issues with parsing it in Ruby. Despite trying various methods and conducting extensive research, I have not been able to find a solution.
It is important to note that I am relatively new to Ruby.
Here are my attempts:
def initialize(game_conf_json)
parsed_conf = JSON.parse(conf_json)
@param1 = parsed_conf['name'][0]
@param2 = parsed_conf['surname'][0]
=begin
I also tried this:
@param1 = parsed_conf['name']
@param2 = parsed_conf['surname']
However, no matter what approach I take, I keep encountering the error message:
"21:in `[]': can't convert String into Integer (TypeError)"
OR
"can't convert Array into String (TypeError), "
=end
File.open("some_direc/conf.json", "w") do |f|
f.write(game_conf_json)
end
end
In JavaScript, I generate the JSON as follows:
var json_of_form_vars = {};
json_of_form_vars.name = name_val;
json_of_form_vars.surname = surname_val;
And then send it using the following method:
$.ajax({
url: "../fundament/dispatch.rb/",
type: "post",
dataType: "json",
data: "conf="+json_of_form_vars,
.....
How can I resolve this issue? Are there any helpful tutorials available for solving this problem?
UPDATE1 (After suggestions): I utilized JSON.stringify to pass the object to Ruby successfully. The output in Ruby looks like this:
{"name": "METIN", "surname": "EMENULLAHI"}
Although the .class method indicates it's an array, traditional means of accessing data such as 'array['name']' result in the error:
can't convert String into Integer
Even when attempting to use JSON.parse on conf_array.to_json, I encounter similar errors related to arrays:
can't convert Array into String
What steps should be taken next?
UPDATE2 The CGI handler responsible for passing URL parameters to relevant locations is presented below:
cgi_req = CGI::new
puts cgi_req.header
params_from_request = cgi_req.params
logger.error "#{params_from_request}"
action_todo = params_from_request['action'][0].chomp
base = Base.new
if action_todo.eql?('create')
conf_json = params_from_request['conf']
# This line prints the json like this: {"name": "SOME_NAME", "surname": "SOME_SURNAME"}
logger.error "#{conf_json}"
base.create_ident(conf_json)
end
And in the Base class:
def create_ident(conf_json)
require 'src/IdentityCreation'
iden_create = IdentityCreation.new(conf_json)
end
The constructor for IdentityCreation is outlined above.
UPDATE3:
Progress has been made in extracting information from the array. However, accessing a key results in displaying the key itself:
parsed_conf = JSON.parse(conf_json.to_json)
@param1 = parsed_conf[0]['name']
@param2 = parsed_conf[0]['surname']
# When printing @param1 at this stage, it returns "name" (the key) rather than "SOME_NAME" (the value).