crystal-lang / crystal-mysql

MySQL connector for Crystal
MIT License
107 stars 36 forks source link

Converting MySql::ResultSet to JSON::any #42

Closed kazzkiq closed 7 years ago

kazzkiq commented 7 years ago

I'm trying to run a simple code and return a JSON with the results:

DB.open("mysql://root@localhost:3306/mydb") do |db|
  db.query "SELECT name FROM users" do |result|
    result.to_json
  end
end

But I get this error when trying to use .to_json on the results:

no overload matches 'MySql::ResultSet#to_json' with type JSON::Builder

Any idea on how can I convert my query results to JSON? I can't find any documentation describing it, and its literally the only thing keeping me from releasing a small Crystal API module into production.

bcardiff commented 7 years ago

Crystal stdlib does not has a Object#to_json. Depending on your use case you might need to use a JSON::Builder or use JSON.mapping docs.

You might find https://manas.tech/blog/2017/01/16/from-a-db-to-json-with-crystal.html useful.