views:

210

answers:

2

Hello all,

I have an array of hashes in a Rails action which i return to client in json format:

{"msg": "Got report data.Check 'report' json object. ", "success": true, "reports": "[{\"total_transfers\": 0, \"total_keywords\": 0, \"keyword\": \"plum\", \"total_duration\":1464.0, \"total_calls\": 22, \"total_sms\": 0, \"avg_duration\": 67,\"total_email\": 0}]"}

In action i do: return reports.to_json but as you can see it does not look like valid json (why the escape characters?)

In client side js code, i do reports.length and get 163??? when it should say 1 because there is only one "report" in the reports array.

A: 

As you can see "reports" is one big string, instead of an array of a hash which you'd expect (163 is the length of the string, and this is why you can see escape characters). Which json library are you using with rails? What kind of object is your array of hash exactly? It might not have the to_json method implemented...

Alternatively you might try to convert your repsonse to yaml first, from that getting json is easier.

SztupY
yup. just realized that "reports" is just a string and that 163 is the length of the string. not sure where to look for which json lib i am using?? my array of hashes are of string type.Not sure how to convert to yaml. besides i thought i could go directly from ruby hash object to proper json??
rafael
A: 
reports_array_object = eval("(" + reports + ")");

sweet!!!!

rafael