Parsing JSON data received through a URL using Ruby

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).

Answer №1

If you're struggling with parsing a JSON string, consider sharing the generated JSON for further assistance.

require 'json'
require 'ap'

string = %{
  {"configurations" : [ 
  { "drinks" : [
          {"menus" : [
            { "hot" : [
              {"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 4},
              {"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 6}
            ] },

            { "cold" : [
          {"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 4},
              {"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 6}
             ] },

            { "terminals" : { "id" : 4, "id": 6, "id": 7 } }, 

            { "keys" : { "debit" : "on", "credit": "off" }  }

          ] }
  ] } ] } 
}

hash = JSON.parse(string)
ap hash

This will display:

{
    "configurations" => [
        [0] {
            "drinks" => [
                [0] {
                    "menus" => [
                        [0] {
                            "hot" => [
                                [0] {
                                          "id" => 15,
                                        "unit" => "0.33",
                                       "price" => "1",
                                    "currency" => "Euro",
                                    "position" => 4
                                },

and so on.

Answer №2

Currently, you are not actually sending JSON data. Instead, you are attempting to send JSON wrapped inside form-encoded parameters. Furthermore, when you use

"conf=" + json_of_form_vars

JavaScript will automatically convert json_of_form_vars to a string, but this conversion is not the same as converting it to JSON format. JavaScript's default string conversions may not be suitable for objects, so you should use JSON.stringify to properly convert it to JSON.

When constructing the body as a string literal, you must also ensure that any special characters that are not allowed (or have special meanings) in this context are escaped. It is usually easier to rely on jQuery for this task, like so:

$.ajax({
    url: "../fundament/dispatch.rb/",
    type: "post",
    dataType: "json",
    data: {conf: JSON.stringify(json_of_form_vars)}

Answer №3

I've finally cracked it! After taking into account all the advice given in this thread and drawing from my own experiences with irb, hashes, arrays, and JSON.

Instead of converting my object (conf_json) to JSON (using to_json), I opted to pass it as a string to JSON.parse like so:

parsed_conf = JSON.parse(%{#{conf_json}})

It may seem unconventional, as when I tried passing it directly to the function like below, I encountered the error can't convert Array into String.

parsed_conf = JSON.parse(conf_json)

However, it's currently functioning perfectly for me.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Best method for linking asynchronous requests using axios

Is it possible to make an API call using axios based on the response of another initial API call, all within asynchronous functions? I attempted the following approach with await/promise: function fetchUserDetails(userId) { return axios.get( "https://a ...

When transferring JSON to JavaScript within Laravel, the JSON data gets converted into HTML entities by JavaScript

Within my Laravel controller, I am constructing a multidimensional associative array: $trendChart = Array ( "series" => Array ( "data" => Array(1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5) ), "xaxis" => Arr ...

Is it possible for a button to simultaneously redirect and execute a function using asynchronous JavaScript?

After browsing through several related posts, I realized that most of them were using href to redirect to a completely new webpage. However, in my JavaScript code, I have a button that utilizes the Material-UI <Link>. <Button component={Link} to= ...

Difficulty with Pomodoro clock's canvas ring function not working as expected

Hey everyone, good evening. I've been struggling with a particular section of code for quite some time now and could really use some help. When you check out the constructor at this.drawArc and then look into the prototype, I've printed a couple ...

Are there any modules in Angular 8 that are used across various projects?

I am facing a challenge with managing two projects that share the same core functionality. These projects have identical layouts and pages, but certain components and modules are specific to each project. Currently, I maintain two separate Angular projects ...

Unpacking Objects in JavaScript and TypeScript: The Power of Destructuring

I have a variable called props. The type includes VariantTheme, VariantSize, VariantGradient, and React.DOMAttributes<HTMLOrSVGElement> Now I need to create another variable, let's name it htmlProps. I want to transfer the values from props to ...

Learn how to effectively showcase various components by leveraging the new react-router-dom v6.0.0 alongside react-redux

My issue is that when I click on a link to render different components, the URL updates but the UI remains unchanged. No matter which item I click on to render, the same thing happens. I've tried numerous solutions to fix this problem without success. ...

Converting SQL Select Queries into JSON for Organizing Menu Layout

I need assistance with a query that can generate JSON output for creating a menu structure. I want to populate the Menu using this JSON data. Below are the details of the two tables I am working with and the query I have tried so far: SELECT c.ID As ...

The fullcalendar is experiencing difficulties in showing the event

I am facing an issue with Fullcalendar where the events fetched by ajax are not showing up on the calendar. Even though the events are successfully passed and can be displayed in a pop-up, they do not render on the calendar. When manually setting the event ...

Locate the row just before the last one in the table

I have a table that dynamically creates rows, and I need to locate the second to last row in the table. HTML Code <table class="table"> <tr><td>1</td></tr> <tr><td>2</td>< ...

Is there a way to capture the click event of a dynamically generated row within a panel?

Could you please advise on how to capture the click event of a row that is generated within a panel? I have successfully captured events for rows generated on a page using the , but now I need assistance with capturing events from rows within a panel. I c ...

Decipher JSON information when retrieving data from a MySQL database

Can we directly retrieve decoded data from a MySQL database column where the information is stored as JSON encoded text? Is there a way to fetch already decoded data in the select query instead of extracting the JSON encoded text and decoding it separate ...

Issue with debugging capabilities in Javascript on VSCode has been detected

UPDATE: I'm seeking guidance on configuring VSCode for debugging Javascript. While I'm familiar with JavaScript functioning in a browser, I find it tedious to rely solely on console.log(). I am looking to debug and step through my code effectivel ...

Handling every promise in an array simultaneously

I am facing a problem with my array inside Promise.all. When I try to execute a function for the last iteration of forEach loop, I notice that my count_answers variable is only being set for the last object. This can be seen in the log output; the count_an ...

Attempting to access a variable from outside the function

I am looking to pass the index variable from mapping to the event change function in my code snippet below: {this.data && this.data.map((item, index) => ( <tr className="table-info" key={index}> <td>{index}</ ...

Is there a way to seamlessly update button values in VueJs from an api request without needing to reload the page or manually clicking something? Or perhaps there is an alternative method to achieve this?

I attempted to solve the issue by implementing while(true) within the created method so that it constantly updates by sending frequent requests to Flask. Is there a different approach to updating my value? Vue: let app = Vue.createApp({ data ...

What is the best way to instruct firebase-admin to halt during test execution?

Running process.exit() or --exit in my mocha tests doesn't feel right. I'm currently working on code that utilizes firebase-admin and while attempting to run mocha tests, wtfnode showed me: wtfnode node_modules/.bin/_mocha --compilers coffee:co ...

What is the process of setting up Express as an API web server and integrating a custom document renderer as middleware?

I have developed a code generator and I want to be able to execute it on the server. The generator utilizes pure native ECMA6 JavaScript to render HTML markup, but it is transpiled to ES5 before runtime using Babel and WebPack. I am looking to use this on ...

What is the best way to adjust the size of a Div slideshow using

I need help with creating a slideshow that covers my webpage width 100% and height 500px. The image resolution is 1200*575. Can someone assist me with this? CSS #slide{ width : 100%; height: 500px; } HTML <!DOCTYPE html> <html> ...

Code snippet that will emphasize the active page if there are multiple pages, such as highlighting page 2

My current project involves implementing a script to highlight the current page on a Tumblr blog. I found the script I am using here: $(function(){ $('a').each(function() { if ($(this).prop('href') == window.location.href) { ...