[英]Convert CSV to JSON key value
I have a CSV file like this: 我有这样的CSV文件:
First Name*,Registrarse
Last Name*,Registrarse
Your Email*,Nombre*
Country*,Apellido*
I am looking for someway to convert this to JSON like this: 我正在寻找某种将其转换为JSON的方法,如下所示:
{
"First Name*": "Registrarse",
"Last Name*": "Registrarse"
.....
}
I tried NPM tools like CSV to JSON and I could not get this effect. 我尝试了NPM工具(例如CSV到JSON),但无法获得这种效果。 Does anyone know a way to do this?
有人知道这样做的方法吗?
You could turn the CSV file into an associative array and encode that as JSON: 您可以将CSV文件转换为关联数组,并将其编码为JSON:
$csv = <<<EOF
First Name*,Registrarse
Last Name*,Registrarse
Your Email*,Nombre*
Country*,Apellido*
EOF;
$csvArray = explode(PHP_EOL, $csv);
$jsonArray = array();
foreach ($csvArray as $row) {
preg_match('/(.*?),(.*)/', $row, $matches);
$jsonArray[$matches[1]] = $matches[2];
}
$json = json_encode($jsonArray, JSON_PRETTY_PRINT);
echo $json, PHP_EOL;
Output: 输出:
{
"First Name*": "Registrarse",
"Last Name*": "Registrarse",
"Your Email*": "Nombre*",
"Country*": "Apellido*"
}
Coming a bit late into this thread but in case it interests some other future user. 稍晚一些,但以防其他未来用户感兴趣。 I created a tiny in-browser app able to handle that.
我创建了一个微型浏览器应用程序,可以处理该问题。
Just go to csvtojson.com and paste your csv, it will be output to you as needed. 只需转到csvtojson.com并粘贴您的csv,它将根据需要输出到您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.