简体   繁体   中英

Convert CSV to JSON key value

I have a CSV file like this:

First Name*,Registrarse
Last Name*,Registrarse
Your Email*,Nombre*
Country*,Apellido*

I am looking for someway to convert this to JSON like this:

{
  "First Name*": "Registrarse",
  "Last Name*": "Registrarse"
   .....
}

I tried NPM tools like CSV to JSON and I could not get this effect. Does anyone know a way to do this?

You could turn the CSV file into an associative array and encode that as 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM