2

I have a rails application where I have JSON data as shown below:

{"makes":[{"id":200347864,"name":"AM General","niceName":"am-general","models":[{"id":"AM_General_Hummer","name":"Hummer","niceName":"hummer","years":[{"id":3407,"year":1998},{"id":1140,"year":1999},{"id":305,"year":2000}]}]}]}

This is a very long list of car objects with multi-levels of nesting. Make, model, year, trim etc.

I want to send this JSON to javascript and populate my autofill drop down menu.

Previously, I was using a third-party API and the code looked like:

$( document ).ready(function() {


    var prev ="https://xyz/makes";
    var rest ="?fmt=json&api_key=";
    var key = "<%= ENV['XYZ_API_KEY'] %>";
    var net = prev+rest+key;

    var options = [];
    options.push("All");
    var dictionary = {};

         $.ajax({

            url: net,
            dataType: "json",
            type: "get", 
            data: $(this).serialize()
         }).done(function(data){
            change_make(data);
            change_model();
         });




    function change_make(data) {

        for (var key in data["makes"]){
            if (data["makes"].hasOwnProperty(key)){

                var make = data["makes"][key];

                options.push(make.name);

                buffer = [];

                // console.log(make.models);

                for (var key2 in make.models){

                    // console.log(make.models[key2].name);

                    if (make.models.hasOwnProperty(key2)){

                        // console.log(make.models[key2].name);

                        buffer.push(make.models[key2].name);
                    }

                }


                dictionary[make.name] = buffer;

            }
        }

        dictionary["All"] = ["All"]

        // console.log(options);

        $.each(options, function(key, value) {   
             $('#category')
                 .append($("<option></option>")                            
                    .attr("value", value.html_safe)
                    .text(value));  
        });    

    };



    $('#category').on('change', function(){


        console.log("change success");

        change_model();



    });


    function change_model(){

        var make = $('#category').find(":selected").text();        
        var models = dictionary[make];
        // models.unshift("All");

        $('#subcategory').empty();

        $.each(models, function(key, value) {   
             $('#subcategory')                
                 .append($("<option></option>")                            
                    .attr("value",value.html_safe)
                    .text(value));  
        });
    }    

    $("#searchboxcontainer").delay(100).fadeIn(200);   


});

Instead of using the ajax request, I want to use json string directly. I wrote a helper method in application helper module as shown:

 def edmunds_json      
  the_json_object
 end

But when I am using it in javascript, its adding &gm characters and theobject comes out as:

{:makes=&gt;[{:id=&gt;200347864, :name=&gt;&quot;AM General",...

and the code is giving errors

Uncaught SyntaxError: Unexpected token :

When I am using escape in JSON, it's giving me the error on rails unexpected $undefined. expecting ').

The JSON object is using double quotes and I want to use it in my code. How should I proceed so &gt etc won't be added.

8
  • did you try to parse the object using JSON.parse ? Commented Feb 22, 2018 at 22:16
  • Yes. But then it gave the error unexpected tIDENTIFIER "}". expected end Commented Feb 22, 2018 at 22:21
  • do you convert your data to json string from your backend before sending it to javascript function, using .to_json ? Commented Feb 22, 2018 at 22:25
  • No its an object available already. Beforehand I was using external API. Now I have the object available without a call to the database. Commented Feb 22, 2018 at 22:28
  • 1
    yes, but where is that edmunds_json method being called? Commented Feb 22, 2018 at 22:35

2 Answers 2

2

I think what you need to do is to first convert your Ruby Hash into json in your helper

def edmunds_json      
  the_json_object.to_json
end code here

Then in your view in a script tag do something like this

<script>
  const object = <%= raw edmunds_json %>
  console.log(typeof(object)) // => Object
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

Solved it by using:

<%= get_make_model_json.to_s.gsub("=>",":").html_safe %>; in javascript

where get_make_model_json is:

def get_make_model_json      
      JSON.parse(
        '{
  "makes": [{
    "id": 200347864,
    "name": "AM General",
    "niceName": "am-general",
    "models": [{
      "id": "AM_General_Hummer",
      "name": "Hummer",
      "niceName": "hummer",
      "years": [{
        "id": 3407,
        "year": 1998
      }, {
        "id": 1140,
        "year": 1999
      }, {
        "id": 305,
        "year": 2000
      }]
    }]
  },...
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.