remove quotes from jbuilder json

孤者浪人 提交于 2020-01-07 02:32:10

问题


I'm new to rails and jbuilder, so I'm not sure if this is doable or not. I'm using this autocomplete jquery plugin http://www.devbridge.com/sourcery/components/jquery-autocomplete/ and the response it expects is to be in the format of

{
    query:'Li',
    suggestions:['Liberia', 'Libyan Arab Jamahiriya', 'Liechtenstein', 'Lithuania'],
    data:['LR', 'LY', 'LI', 'LT']
}

When I try to use jbuilder to return json, I'm getting back a json object with both the keys and values in quotes like

{"query":"Comp","suggestions":"['Test Company','Test Company 2','Test company','tester chester','before create test']","data":"['1','2','3','4','5']"}

It appears that this is causing the plugin to not work, so is there a way I can remove the double quotes from the returned json? Here's what my jbuilder file looks like.

suggestions = ""
data = ""

@companies.each do |company|
  suggestions += "'" + company.name + "',"
  data += "'" + company.id.to_s + "',"
end

json.query @query
json.suggestions "[" + suggestions[0...-1] + "]"
json.data "[" + data[0...-1] + "]"

Thanks!


回答1:


I figured out the solution (or a coworker and I did;) The jbuilder code was changed to this. Rather than creating a string I needed to give the json builder an array.

suggestions = []
data = []

@companies.each do |company|
  suggestions.push(company.name)
  data.push(company.id)
end

json.query @query
json.suggestions suggestions
json.data data


来源:https://stackoverflow.com/questions/23388635/remove-quotes-from-jbuilder-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!