RoR: to_json on an array of hashes

Go To


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.

2009-06-16 13:45
by Rafael
can you show us the code where you're building this array? It looks like you've double-serialized the reports object - austinfromboston 2009-06-16 17:58


reports_array_object = eval("(" + reports + ")");


2009-06-16 14:51
by Rafael


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.

2009-06-16 13:50
by 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 2009-06-16 14:05