So Im trying to extract nodes from my database (by going through it recursively) and then displaying the json code i have to a javascript library. The problem is that the library is not identifying the json array output because it has extra quotation marks and a slash (/). Here is the code:
data = {
"nodes":
"\"User1:{'color':'green','shape':'dot','label':'You'},
User2:{'color':'green','shape':'dot','label':'You'},
User3:{'color':'green','shape':'dot','label':'You'}\""
,"edges":{}};
And I want it to look something like this:
var data = {
"nodes":{
"You":{'color':'green','shape':'dot','label':'You'},
Ben:{'color':'black','shape':'dot','label':'Ben'},
David:{'color':'black','shape':'dot','label':'David'}
},
"edges":{
You:{ Ben:{}, David:{} },
Ben:{ David:{}}
}
};
In my user_controller I am using this:
def make_json(node, string = "")
node[1].each do |n|
string += node[0] + "{'color':'green','shape':'dot','label':'You'},"
return make_json(n, string )
end
return string + node[0] + "{'color':'green','shape':'dot','label':'You'}"
end
And finally, this:
@data = {}
@data['nodes'] = make_json(@user_tree[0]).to_json
@data['edges'] = {}
I tried using the replace method, but the data variable doesnt seem to be a String so I can’t just replace the quotation marks. I’d appreciate any sort of help.
Thanks!
The reason for the extra
\"in the output is that you are callingto_jsonon the return value from yourmake_jsonmethod which is a string.Its hard to see exactly what you are trying to do in
make_json, but assuming that you want to use the output as a value in your@datahash and then convert that to json I think you would be better off havingmake_jsonbuild a hash and return that. Generally when returning a JSON response the easiest solution is to build a data structure out of Ruby hashes and arrays and then callto_jsonon that. Here is a much simplified example (I don’t know what the@user_treeis so I don’t understand the recursive step but I hope this gives you the general idea):If you try to construct the JSON string yourself it is easy to trip up. The output that you say you are aiming for is not valid JSON though it may be valid JavaScript. Strings need to be wrapped in double quotes, e.g.
rather than: