Joh*_*ohn 14 php mysql import json facebook
我面临的问题是将JSON导入Mysql.我搜索了互联网,我搜索了stackoverflow,可能还有更多来源,但找不到合适的解决方案.完全披露 - 我不是PHP,SQL,也不是JSON专业人士.
我想要完成的工作非常简单:将此JSON文件https://developers.facebook.com/tools/explorer/method=GET&path=245226895508982%2Ffeed%3Faccess_token%3D%3Caccess_token%3E= 导入Mysql数据库.我知道我需要以某种方式将JSON数据分配到列中,然后根据内容相应地策划行.我不需要所有的数据,但大部分数据.稍后应通过用户的搜索查询回显数据.
我的问题似乎很简单 - 我该怎么做?
PS:我尝试将其转换为XML,但我没有足够的权限将XML导入SQL数据库.转换器也不是最好的工作.
kma*_*mas 11
您可以将json导出到csv:http://www.danmandle.com/blog/json-to-csv-conversion-utility/或https://github.com/danmandle/JSON2CSV
然后 :
LOAD DATA INFILE 'filepath/your_csv_file.csv' INTO TABLE tablename;
Run Code Online (Sandbox Code Playgroud)
对于一个人来说应该没问题.
有关load data infile的更多信息.
就像其他人所说的那样,你将不得不做一些转换来做你所要求的.幸运的是,让PHP迭代数据并为您完成大部分工作并不困难.这是一个快速而又肮脏的尝试:
// MySQL table's name
$tableName = 'my_table';
// Get JSON file and decode contents into PHP arrays/values
$jsonFile = '/path/to/file.json';
$jsonData = json_decode(file_get_contents($jsonFile), true);
// Iterate through JSON and build INSERT statements
foreach ($jsonData as $id=>$row) {
$insertPairs = array();
foreach ($row as $key=>$val) {
$insertPairs[addslashes($key)] = addslashes($val);
}
$insertKeys = '`' . implode('`,`', array_keys($insertPairs)) . '`';
$insertVals = '"' . implode('","', array_values($insertPairs)) . '"';
echo "INSERT INTO `{$tableName}` ({$insertKeys}) VALUES ({$insertVals});" . "\n";
}
Run Code Online (Sandbox Code Playgroud)
这将吐出一系列INSERT INTO my_table(...)VALUES(...); 可以保存为.sql文件并导入MySQL的SQL语句.使用此方法,每个INSERT可以具有不同的列而不会导致问题.
注意:addslashes()不是一种非常安全的方法,并且像real_escape_string()这样的东西会更好,但是这可以在没有数据库连接的情况下工作,假设你的JSON数据值得信赖.
小智 6
使用MySQL Shell 8.0.13,您可以使用util.importJsonshell API 函数或命令行选项将 JSON 文档直接导入 MySQL 服务器--import。例如从文件导入:
mysqlsh user@host:port/database --import /tmp/facebook.json collection_name
或将 JSON 文档通过管道传输到标准输入:
cat /tmp/facebook.json | mysqlsh user@host:port/database --import - collection_name
这里collection_name是一个集合。
有关 MySQL Shell 的 JSON 导入实用程序的更多信息:https : //dev.mysql.com/doc/mysql-shell/8.0/en/mysql-shell-utilities-json.html
更多关于文档存储:https : //dev.mysql.com/doc/refman/8.0/en/document-store.html
有关文档和集合的更多信息:https : //dev.mysql.com/doc/refman/8.0/en/mysql-shell-tutorial-javascript-documents-collections.html
| 归档时间: |
|
| 查看次数: |
64685 次 |
| 最近记录: |