I am interested in exporting a subset of values from a MySQL database into a JSON-formatted file on disk.
I found a link that talks about a possible way to do this:
Also, If you are exporting in application layer don't forget to limit results. For example if you've 10M rows, you should get results part by part.
Use the following ruby code
require 'mysql2'
client = Mysql2::Client.new(
:host => 'your_host', `enter code here`
:database => 'your_database',
:username => 'your_username',
:password => 'your_password')
table_sql = "show tables"
tables = client.query(table_sql, :as => :array)
open('_output.json', 'a') { |f|
tables.each do |table|
sql = "select * from `#{table.first}`"
res = client.query(sql, :as => :json)
f.puts res.to_a.join(",") + "\n"
end
}
Another possibility is using the MySQL Workbench.
There is a JSON export option at the object browser context menu and at the result grid menu.
More information on MySQL documentation: Data export and import.
This might be a more niche answer but if you are on windows and MYSQL Workbench you can just select the table you want and click Export/Import in the Result grid. This will give you multiple format options including .json
HeidiSQL allows you to do this as well.
Highlight any data in the DATA tab, or in the query result set... then right click and select Export Grid Rows option. This option then allows you can export any of your data as JSON, straight into clipboard or directly to file:
THis is somthing that should be done in the application layer.
For example, in php it is a s simple as
Edit Added the db connection stuff. No external anything needed.
$sql = "select ...";
$db = new PDO ( "mysql:$dbname", $user, $password) ;
$stmt = $db->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
file_put_contents("output.txt", json_encode($result));