如何将CSV数据转换为JSON对象

时间:2014-11-03 08:52:11

标签: javascript php arrays csv d3.js

所以我有这个csv文件(csv文件最好可能位于服务器端,但尚未决定)。很可能会向用户显示从下拉菜单中选择这些csv文件的选项。然后在选择特定文件后,用户单击“输入”,然后应该在javascript中将此选定的csv文件作为数组读取。那怎么办? : -

我的问题是How to pass variables and data from PHP to JavaScript?

___ csv_file ____

Class,      Subclass,           Company,    Product,
Chocolate,  Wafer chocolate,    Nestle, KitKat,
Chocolate,  White chocolate,    Nestle, Milkybar,
Chocolate,  White chocolate,    Nestle, Milkybar,
Chocolate,  Caramel chocolate,  Nestle, BarOne,
Chocolate,  Milk chocolate,     Nestle, Nestle Milk chocolate,
Chocolate,  Milk chocolate,     Nestle, Nestle Milk chocolate,
Chocolate,  Milk chocolate,     Nestle, Nestle Milk chocolate,
Chocolate,  Milk chocolate,     Nestle, Nestle Milk chocolate,
Chocolate,  Milk chocolate,     Cadbury,    Dairy milk,

为了手动阅读,这就是已经完成的工作。但正如你所看到的那样,所有的csv_data都是硬编码的,但我想让它自动化(即通过读取csv文件生成)

    root = {
 "name": "Chocolate", "tag":"class",
 "children": [
  {
   "name": "Wafer", "tag":"subclass",
   "children": [
    {
      "name": "Nestle", "tag":"company",
     "children": [
      {"name": "KitKat", "tag":"product"}
     ]
    }
   ]
  },

  {
   "name": "White", "tag":"subclass",
   "children": [
    {
      "name": "Nestle", "tag":"company",
     "children": [
      {"name": "Milkybar", "tag":"product"}
     ]
    }
   ]
  },

    {
   "name": "Caramel", "tag":"subclass",
   "children": [
    {
      "name": "Nestle", "tag":"company",
     "children": [
      {"name": "BarOne", "tag":"product"}
     ]
    }
   ]
  },    
    {
   "name": "Milk", "tag":"subclass",
   "children": [
    {
      "name": "Nestle", "tag":"company",
     "children": [
      {"name": "Nestle Milk", "tag":"product"}
     ]
    },  {
      "name": "Cadbury", "tag":"company",
     "children": [
      {"name": "Dairy Milk", "tag":"product"}
     ]
    }
   ]
  }




 ]
};

现在的问题是我希望javascript只是从本地位置读取这个csv文件。但是有可能在JAVASCRIPT中将CSV文件读入这样一个复杂的维数组吗?

2 个答案:

答案 0 :(得分:1)

可能的设置:

PHP Web服务器(或NodeJS服务器 - 我个人最喜欢的)

可能的工作流程:

  • 用于CSV文件的php上传页面/或通过FTP / SSH上传
  • csv在服务器上
  • 带有param的php页面datafromid = csvfile提供从csv到json的数据转换..(如果csv文件不包含太多行,将其读入php数组,然后用json_encode()将其吐出来得到每一行(fgetcsv())并在整个数组中添加一个子数组)
  • 取决于你如何向d3提供数据,使用ajax访问该php页面以访问json或将其包含在你的页面中(我认为通过ajax加载它,从页面所在的浏览器访问文件,更好 - 你可以使用jQuery get()

答案 1 :(得分:1)

首先在服务器上创建一个PHP文件,为它提供一个相关的名称,如candyData.php,你可以在其中:

//code to read your data.csv
//code which stores the data from the csv into an object $candyData
$json = json_encode($candyData);
return $json

然后在客户端使用Javascript,我也将使用JQuery:

jQuery.ajax({
    url: "http://example.mysite.com/rest/candyData.php",
    type: "GET",
    success: function (response) {
        var candyData = response;
        //Here you'd put all the code you currently have so you can visualize the data
    },
    error: function (response) {
        console.log("failed");
    }
});