简体   繁体   中英

RoR: to_json on an array of hashes

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.

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.

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

sweet!!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM