我有一个JSON服务,需要创建一个脚本来将数据导出到CSV文件。有没有人可以建议将JSON迁移到CSV格式的方法或库?
下面是一个示例格式,不过我希望必须重新调整解决方案才能使用它:
{"service_name":
{ key : value, key : value....}
}
或:
{"service_name":
[
{ key : value, key : value....},
...
]
}
我通常同意评论者的观点,但如果你的数据是这样准备的,这不是你所需要的全部伪代码吗?
$json_str = "{'aintlist':[4,3,2,1], 'astringlist':['str1','str2']}";
$json_obj = json_decode ($json_str);
$fp = fopen('file.csv', 'w');
foreach ($json_obj as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
假设您的JSON是一个没有数组或嵌入对象的数据集数组,这样的操作应该有效:
$file = file_get_contents('http://example.com/blah/blah');
$json = json_decode($file);
$csvfile = fopen('file.csv', 'w+');
foreach ($json as $row) {
$line = "'" . join("'",'"", $row) . "'"'n";
fputs($csvfile, $line);
}
fclose($csvfile);
您必须添加适当的错误处理。当尝试做这种事情时,有很多事情可能会出错(即JSON文件不可用或格式错误,无法创建新的CSV文件)
我只需要做同样的事情。我编写了一个小的命令行脚本,它将json文件作为参数并输出CSV。
您可以在这里查看:PHP将JSON数组转换为CSV
那里的重要人员使用数组的键作为CSV文件中的第一行。并维护下一个元素的顺序,以免弄乱CSV。
这是代码:
if (empty($argv[1])) die("The json file name or URL is missed'n");
$jsonFilename = $argv[1];
$json = file_get_contents($jsonFilename);
$array = json_decode($json, true);
$f = fopen('php://output', 'w');
$firstLineKeys = false;
foreach ($array as $line)
{
if (empty($firstLineKeys))
{
$firstLineKeys = array_keys($line);
fputcsv($f, $firstLineKeys);
$firstLineKeys = array_flip($firstLineKeys);
}
// Using array_merge is important to maintain the order of keys acording to the first element
fputcsv($f, array_merge($firstLineKeys, $line));
}