Dave Dave - 6 months ago 26
JSON Question

"no implicit conversion of Array into String" when trying to parse JSON data

I’m using Rails 4.2.3. I’m trying to parse JSON data, so I have

content = ["{\"sEcho\":3,\"timestamp\":1464705752942,\"iTotalRecords\":1242,\"iTotalDisplayRecords\":1242,\"aaData\":[{\"externalId\":\"4279\"}]}"]
my_object_times_array = JSON.parse(content)


Sadly, the second line gives the error

no implicit conversion of Array into String


The JSON is well-formed (at least as far as I can tell) so I’m not sure what is causing the error above and how to fix it. I would prefer not to change the JSON.

Answer

content is an array, but JSON.parse expects a JSON String.

Example of usage from the documentation:

require 'json'

my_hash = JSON.parse('{"hello": "goodbye"}')
puts my_hash["hello"] => "goodbye"

Check the documentation here

So you could do following:

content = "{\"sEcho\":3,\"timestamp\":1464705752942,\"iTotalRecords\":1242,\"iTotalDisplayRecords\":1242,\"aaData\":[{\"externalId\":\"4279\"}]}"
my_object_times_array = JSON.parse(content)

or

content = ["{\"sEcho\":3,\"timestamp\":1464705752942,\"iTotalRecords\":1242,\"iTotalDisplayRecords\":1242,\"aaData\":[{\"externalId\":\"4279\"}]}"]
my_object_times_array = JSON.parse(content[0])
Comments