我有兴趣将值的子集从MySQL数据库导出到磁盘上的JSON格式的文件中。
我找到了一个讨论执行此操作的方法的链接:http : //www.thomasfrank.se/mysql_to_json.html
…但是当我使用该页面中的方法时,它似乎可以工作,但是有两个问题:
1)它只返回大约15个结果,最后一个突然中断(不完整)。当我按以下方式运行时,我对此的标准查询返回大约4000个结果,SELECT name, email FROM students WHERE enrolled IS NULL 但是当我按以下方式运行时:
SELECT name, email FROM students WHERE enrolled IS NULL
SELECT CONCAT("[", GROUP_CONCAT( CONCAT("{name:'",name,"'"), CONCAT(",email:'",email,"'}") ) ,"]") AS json FROM students WHERE enrolled IS NULL;
…如链接中所述,它仅返回(如我所述)15个结果。(一开始,我对照应该得到的4000来检查了这些结果,而这15个结果与4000的前15个结果相同)
2)当我添加INTO OUTFILE '/path/to/jsonoutput.txt' FIELDS TERMINATED BY ','到该查询的末尾时,实际文件中似乎包含“转义”字符。因此,逗号最终看起来像“ \”,而显然我只希望逗号不带有\。
INTO OUTFILE '/path/to/jsonoutput.txt' FIELDS TERMINATED BY ','
关于如何从MySQL获取正确的JSON输出的任何想法?(使用此方法还是其他方法)?
谢谢!
可能要求MySQL太多的人期望MySQL直接从查询中生成格式正确的json。相反,可以考虑生成更方便的内容,例如CSV(使用INTO OUTFILE '/path/to/output.csv' FIELDS TERMINATED BY ','您已经知道的摘录),然后将结果转换为使用内置支持的语言(如python或php)的json。
INTO OUTFILE '/path/to/output.csv' FIELDS TERMINATED BY ','
*使用优良的SQLAlchemy *编辑 python示例:
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)