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:
I know this is old, but for the sake of somebody looking for an answer...
There's a JSON library for MYSQL that can be found here You need to have root access to your server and be comfortable installing plugins (it's simple).
1) upload the lib_mysqludf_json.so into the plugins directory of your mysql installation
2) run the lib_mysqludf_json.sql file (it pretty much does all of the work for you. If you run into trouble just delete anything that starts with 'DROP FUNCTION...')
3) encode your query in something like this:
SELECT json_array(
group_concat(json_object( name, email))
FROM ....
WHERE ...
and it will return something like
[
{
"name": "something",
"email": "someone@somewhere.net"
},
{
"name": "someone",
"email": "something@someplace.com"
}
]
Using MySQL Shell you can out put directly to JSON using only terminal
echo "Your SQL query" | mysqlsh --sql --result-format=json --uri=[username]@localhost/[schema_name]
It may be asking too much of MySQL to expect it to produce well formed json directly from a query. Instead, consider producing something more convenient, like CSV (using the INTO OUTFILE '/path/to/output.csv' FIELDS TERMINATED BY ','
snippet you already know) and then transforming the results into json in a language with built in support for it, like python or php.
Edit python example, using the fine SQLAlchemy:
class Student(object):
'''The model, a plain, ol python class'''
def __init__(self, name, email, enrolled):
self.name = name
self.email = email
self.enrolled = enrolled
def __repr__(self):
return "<Student(%r, %r)>" % (self.name, self.email)
def make_dict(self):
return {'name': self.name, 'email': self.email}
import sqlalchemy
metadata = sqlalchemy.MetaData()
students_table = sqlalchemy.Table('students', metadata,
sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column('name', sqlalchemy.String(100)),
sqlalchemy.Column('email', sqlalchemy.String(100)),
sqlalchemy.Column('enrolled', sqlalchemy.Date)
)
# connect the database. substitute the needed values.
engine = sqlalchemy.create_engine('mysql://user:pass@host/database')
# if needed, create the table:
metadata.create_all(engine)
# map the model to the table
import sqlalchemy.orm
sqlalchemy.orm.mapper(Student, students_table)
# now you can issue queries against the database using the mapping:
non_students = engine.query(Student).filter_by(enrolled=None)
# and lets make some json out of it:
import json
non_students_dicts = ( student.make_dict() for student in non_students)
students_json = json.dumps(non_students_dicts)