我有从http://api.wunderground.com/weatherstation/WXDailyHistory.asp?ID=IHAMPSHI46&month=3&day=25&year=2011&format=1返回的CSV数据,需要将其转换为一种格式,我可以根据第一列中的时间选择其中一行。
转换为struct / array / xml会更好吗?最好的方法是什么?
答案 0 :(得分:2)
好的,我转储了结果,看起来CSV文件使用<br>
标记来表示换行符,因此您必须自行转换。以下是使用cflib中的UDF的示例:
<cfscript>
/**
* Transform a CSV formatted string with header column into a query object.
*
* @param cvsString CVS Data. (Required)
* @param rowDelim Row delimiter. Defaults to CHR(10). (Optional)
* @param colDelim Column delimiter. Defaults to a comma. (Optional)
* @return Returns a query.
* @author Tony Brandner (tony@brandners.com)
* @version 1, September 30, 2005
*/
function csvToQuery(csvString){
var rowDelim = chr(10);
var colDelim = ",";
var numCols = 1;
var newQuery = QueryNew("");
var arrayCol = ArrayNew(1);
var i = 1;
var j = 1;
csvString = trim(csvString);
if(arrayLen(arguments) GE 2) rowDelim = arguments[2];
if(arrayLen(arguments) GE 3) colDelim = arguments[3];
arrayCol = listToArray(listFirst(csvString,rowDelim),colDelim);
for(i=1; i le arrayLen(arrayCol); i=i+1) queryAddColumn(newQuery, arrayCol[i], ArrayNew(1));
for(i=2; i le listLen(csvString,rowDelim); i=i+1) {
queryAddRow(newQuery);
for(j=1; j le arrayLen(arrayCol); j=j+1) {
if(listLen(listGetAt(csvString,i,rowDelim),colDelim) ge j) {
querySetCell(newQuery, arrayCol[j],listGetAt(listGetAt(csvString,i,rowDelim),j,colDelim), i-1);
}
}
}
return newQuery;
}
</cfscript>
<cfset u = "http://api.wunderground.com/weatherstation/WXDailyHistory.asp?ID=IHAMPSHI46&month=3&day=25&year=2011&format=1" />
<cfhttp url="#u#" result="csv" />
<!--- if you dump the result you can see that the result contains <br> tags to indicate new lines --->
<!---
<cfdump var="#csv.fileContent#" />
--->
<cfdump var="#csvToQuery(replace(csv.fileContent, "<br>", "", "all"))#" />
答案 1 :(得分:1)
查看cfhttp的文档。使用name属性,您将从http调用中获得一个查询。然后,您可以对结果进行查询查询。
答案 2 :(得分:0)
您的CSV结果正在使用&lt; br&gt;而不是linebreak。 使用此cflib函数http://www.cflib.org/udf/CSVToQuery
答案 3 :(得分:0)
使用H2数据库(www.h2database.com),您可以使用非常方便的csvread功能。 http://cfstuff.blogspot.com/2009/06/using-h2-database-in-coldfusion.html
<cfset u="http://api.wunderground.com/weatherstation/WXDailyHistory.asp?ID=IHAMPSHI46&month=3&day=27&year=2011&format=1"/>
<cfhttp url="#u#" result="csv" />
<cffile
action="write"
file="#ExpandPath('./w3.csv')#"
output="#rereplace(csv.fileContent, "<br>|<!--.*-->", "", "all")#" />
<cfquery name="w2" datasource="h3">
select * from csvread('#ExpandPath('./w3.csv')#')
</cfquery>
<cfdump var=#w2# expand="no"/>
<cfset yesterday = dateadd("d",-1,now())/>
<cfquery name="w2" datasource="h3">
SELECT Time, TemperatureF, WindSpeedMPH FROM csvread('#ExpandPath('./w3.csv')#')
WHERE Time BETWEEN '#dateFormat(yesterday, "YYYY-MM-DD")# #timeFormat(dateAdd("h", -1, yesterday), "HH:MM")#:00' AND '#dateFormat(yesterday, "YYYY-MM-DD")# #timeFormat(dateAdd("h", 1, yesterday), "HH:MM")#:00'
</cfquery>
<cfdump var=#w2#/>