How to export a MySQL database to JSON?

后端 未结 15 1847
感动是毒
感动是毒 2020-12-04 17:52

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:

15条回答
  •  我在风中等你
    2020-12-04 18:05

    Another solution, if you are using Ruby, is to write a connection script to the database with ActiveRecord. You will need to install it first

    gem install activerecord

    # ruby ./export-mysql.rb
    require 'rubygems'
    require 'active_record'
    
    ActiveRecord::Base.establish_connection(
      :adapter => "mysql",
      :database => "database_name",
      :username => "root",
      :password => "",
      :host => "localhost"
    )
    
    class Event < ActiveRecord::Base; end
    class Person < ActiveRecord::Base; end
    
    File.open("events.json", "w") { |f| f.write Event.all.to_json }
    File.open("people.json", "w") { |f| f.write Person.all.to_json }
    

    You can also add methods to the ActiveRecord classes if you want to manipulate data first or include or exclude certain columns.

    Person.all.to_json(:only => [ :id, :name ])
    

    With ActiveRecord you are not limited to JSON. You can just as easily export as XML or YAML

    Person.all.to_xml
    Person.all.to_yaml
    

    You are not limited to MySQL. Any database supported by ActiveRecord (Postgres, SQLite3, Oracle... etc).

    And it's worth mentioning you could open another handle to a database

    require 'active_record'
    
    ActiveRecord::Base.configurations["mysql"] = {
      :adapter  => 'mysql',
      :database => 'database_name',
      :username => 'root',
      :password => '',
      :host     => 'localhost'
    }
    
    
    ActiveRecord::Base.configurations["sqlite3"] = {
      :adapter  => 'sqlite3',
      :database => 'db/development.sqlite3'
    }
    
    class PersonMySQL < ActiveRecord::Base
      establish_connection "mysql"
    end
    
    class PersonSQLite < ActiveRecord::Base
      establish_connection "sqlite3"
    end
    
    
    PersonMySQL.all.each do |person|
        PersonSQLite.create(person.attributes.except("id"))
    end
    

    Here is a quick little blog post about it http://www.seanbehan.com/how-to-export-a-mysql-database-to-json-csv-and-xml-with-ruby-and-the-activerecord-gem

提交回复
热议问题