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=>[{:id=>200347864, :name=>"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 > etc won't be added.
JSON.parse?.to_json?edmunds_jsonmethod being called?