Home > Enterprise >  Parsing JSON in ruby?
Parsing JSON in ruby?

Time:11-02

I have following json:

[{"test": "test_a", "doc_type": { "id": 32 }}]

So I am trying to parse it, but I am receiving error which is

TypeError: no implicit conversion of Array into String.

Sorry I am learning Ruby :D This is the code.

obj = JSON.parse(j)

CodePudding user response:

JSON.parse() expects a string input. So, array can't be used here. Instead you can try as follows,

JSON.parse('[{"test": "test_a", "doc_type": { "id": 32 }}]')

Or

JSON.parse(arrayResponse.to_json)

to_json returns JSON string representation. Doc: https://apidock.com/rails/Hash/to_json

CodePudding user response:

The data structure in your post is not a JSON string that can be parsed but it is a Ruby hash.

If it was a JSON string then parsing would work:

JSON.parse('[{"test": "test_a", "doc_type": { "id": 32 }}]')
#=> [{"test"=>"test_a", "doc_type"=>{"id"=>32}}]

But if you try to JSON parse a Ruby hash then you het exactly the error you describe:

JSON.parse([{"test": "test_a", "doc_type": { "id": 32 }}])
#=> no implicit conversion of Array into String (TypeError)

That probably means that the library you use to load the JSON automatically parses it to a Ruby hash.

  • Related