【问题标题】:Convert Large CSV into multiple JSON arrays of fixed records (eg. 100 records json arrays ) using Shell使用 Shell 将大型 CSV 转换为多个固定记录的 JSON 数组(例如 100 条记录 json 数组)
【发布时间】:2019-11-07 20:18:59
【问题描述】:

如何通过 SHELL 脚本或命令行将大型 CSV 转换为固定记录集的 JSON 数组(100 条记录的 JSON 数组)?

例如。输入 CSV 文件:

identifier,type,locale
91617676848,MSISDN,es_ES
91652560975,MSISDN,es_ES
91636563675,MSISDN,es_ES

预期输出:

1.json  (json array having 100 array records)
  [
  {
    "identifier": "91617676848",
    "type": "MSISDN",
    "locale": "es_ES"
  },
  .
  .
  .
  .
  {
    "identifier": "91652560975",
    "type": "MSISDN",
    "locale": "es_ES"
  }
  ]


  2.json (json array having 100 array records)
  [
  {
    "identifier": "91636563675",
    "type": "MSISDN",
    "locale": "es_ES"
  },
  .
  .
  .
  .

  {
    "identifier": "91636563999",
    "type": "MSISDN",
    "locale": "es_ES"
  }
  ]

【问题讨论】:

    标签: json bash shell csvtojson


    【解决方案1】:

    我创建了一个简单的 php 脚本(我称之为converter.php)。

    您可以按原样调用:php converter.php test.csv 其中 test.csv 包含默认 csv 数据,第一行作为标题。

    <?php
        // open the file passed as parameter
        // Ex: php converter.php test.csv
        // Where test.csv contains the data passed on question
        if (($handle = fopen($argv[1], 'r')) !== false) {
                $count = 0;
                $lines = [];
                while (($data = fgetcsv($handle, 0, ',', '\'')) !== false) {
                        if ($count == 0) {
                            $headers = $data;
                        } else {
                            $lines[] = array_combine($headers, $data);
                        }
                        $count++;
                }
                // Here, separate in array of arrays with 100 elements on each
                // On test i used 2 on second parameter of array_chunk to test with your toy data
                $groups = array_chunk($lines, 100);
                foreach ($groups as $key => $group) {
                        file_put_contents('json_data-'.$key.'.json', json_encode($group));
                }
        }
    

    我在本地运行,并用两个元素分隔文件以对其进行测试,结果在本地保存了两个文件,名为 json_data-&lt;key&gt;.json

    结果在这里:

    • json_data-0.json:

      [ {"identifier":"91617676848","type":"MSISDN","locale":"es_ES"},{"identifier":"91652560975","type":"MSISDN","locale":"es_ES" } ]

    • json_data-1.json:

      [ {"标识符":"91636563675","type":"MSISDN","locale":"es_ES"} ]

    【讨论】:

      【解决方案2】:

      请您尝试awk 解决方案:

      awk -v bs=10 '
          NR == 1 {
              cols = split($0, header, ",")
              next
          }
          {
              if ((NR - 1) % bs == 1) {
                  file = sprintf("%d.json", ++n)
                  print "[\n  {" > file
              } else {
                  print ",\n  {" >> file
              }
              split($0, a, ",")
              for (i = 1; i <= cols; i++) {
                  printf("    \"%s\": \"%s\"", header[i], a[i]) >> file
                  print (i < cols) ? "," : "" >> file
              }
              printf "%s", "  }" >> file
          }
          (NR - 1) % bs == 0 {
              print "\n]" >> file
              close(file)
          }
          END {
              if ((NR - 1) % bs != 0) print "\n]" >> file
          }
      ' input.csv
      

      变量bs 保存每个文件的多个数组。
      它逐行处理输入文件,并且有很多条件分支来生成正确的 json 文件。叹息。

      【讨论】:

        【解决方案3】:

        使用bash 实现,可以通过从文件(2-101、102-201,...)到文件末尾重复切片行范围来完成任务。下面的代码使用sed提取行,使用csvjson将每个块格式化为JSON。

        您可以替换任何您喜欢的工具(很少有 csv 到 json 的替代品)。

        需要的代码稍微冗长一些。

        #! /bin/sh
        csv=$1
        lines=$(wc -l < $csv)
        blocks=$((1+(lines-1)/100))
        for (( i=1 ; i <= blocks ; i++ )) ; do
            sed -ne "1p;$((i*100-98)),$((i*100+1))p" $csv | csvjson -i2 > $i.json
        done
        

        假设文件大小合理,重新处理输入文件不会产生很多开销

        【讨论】:

          猜你喜欢
          • 2020-03-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-09
          • 1970-01-01
          • 2023-04-03
          • 1970-01-01
          • 2018-01-02
          相关资源
          最近更新 更多