Reading *.csv file using JavaScript - javascript

I have a csv file which has the following data format:
2001:200::,2001:200:ffff:ffff:ffff:ffff:ffff:ffff,
42540528726795050063891204319802818560,42540528806023212578155541913346768895,JP,,,36.0000,138.0000,,0,0
2001:208::,2001:208:ffff:ffff:ffff:ffff:ffff:ffff,
42540529360620350178005905068154421248,42540529439848512692270242661698371583,SG,,,1.3667,103.8000,,0,0
I want to only parse the item after the 1st comma (IPv6 address), and the lat/long (36.0000,138.0000 in the first record) values for this record.
How can I use JavaScript/ jQuery to do this?

Use the split method to turn the string into an array and then iterate thru it as you wish.
var csv = "2001:200::,2001:200:ffff:ffff:ffff:ffff:ffff:ffff,4254052872679505006389120431980\n2818560,42540528806023212578155541913346768895,JP,,,36.0000,138.0000,,0,0";
var myArray = csv.split("\n");//You should know what kind of new line your csv is using
myArray.map(function (e) { //Applies this function over each element of myArray that is each line of your csv
var line = e.split(","); //Turn the comma separated string into an array
return "The second element is: " + line[1]; //Do what you need
});

Well the same way you would in any language. First you open the file. Read it line by line. Split each line on the comma. Use the index of the array to get the value you want.
jQuery.get('file.csv', function(data) {
alert(data); // this is a line
var tempArray = data.split(','); // array of data
for(var i = 0; i < tempArray.length; i++)
{
console.log(tempArray[i]); // probably index 1 is your IPv6 address.
}
});

Or just use CSV libraries, I'd suggest PapaParse(Browser) or BabyParse(NodeJS)

Here's what you do :
$.ajax({
type: "GET",
url: "data.csv",
success: function (data) {
var data = Papa.parse(data);
var output = {
"IPv6" : data.data[0][1],
"coordinates" : [data.data[1][5], data.data[1][6]]
} /* -> These are the values you're looking for! */
}
});
Because I can't demo the AJAX (due to cross-domain scripting issues), I'll demo just the success function below!
Demo
var data = '2001:200::,2001:200:ffff:ffff:ffff:ffff:ffff:ffff,'+ "\n" +
'42540528726795050063891204319802818560,42540528806023212578155541913346768895,JP,,,36.0000,138.0000,,0,0'+ "\n\n" +
'2001:208::,2001:208:ffff:ffff:ffff:ffff:ffff:ffff,'+ "\n" +
'42540529360620350178005905068154421248,42540529439848512692270242661698371583,SG,,,1.3667,103.8000,,0,0';
var success = function (data) {
var data = Papa.parse(data);
return output = {
"IPv6" : data.data[0][1],
"coordinates" : [data.data[1][5], data.data[1][6]]
}
}
document.body.innerHTML = '<pre>' + JSON.stringify(success(data), null, 2) + '</pre>';
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>

Related

How do I get the specific part of a URL using jQuery and JavaScript?

I am checking out an order in WordPress via jQuery AJAX. Upon successfully posting, WordPress returns a response to me with a result success value and url value.
I want to get the particular part of this url so I can use the id as an object for my purpose.
This is the structure of the url: http://localhost/mywebsite/checkout/order-received/28564?key=wc_order_5b4dbc6b2f459
This is my current code:
j('.my-checkout').on('submit', function(evt) {
evt.preventDefault();
var billing_customer_type = j("#billing_customer_type").val();
// and so on...
j.ajax({
type: 'POST',
url: 'http://localhost/mywebsite/ajax=checkout',
cache: false,
data: {
'billing_customer_type': billing_customer_type,
// and so on..
},
success: function(result) {
var orderResponseUrl = result.redirect;
j('.order-response-url').html(orderResponseUrl);
// http://localhost/mywebsite/checkout/order-received/28564?key=wc_order_5b4dbc6b2f459
orderResponseUrl.split("/");
console.log(orderResponseUrl[3]);
},
error: function(xhr, status, error) {
console.log(error);
},
complete: function() {}
});
});
The result of my code above is just the the letter "p". I think because it started of the first letter of http and I used the index [3].
Do you know how can I get the specific part of the url that is 28564?
If the URL that you need to interact with is always the same, you can split the returned url at the 'order-received/' portion (which gives an array of everything before that, and everything after it).
Then rather than splitting again on the '?" which is another way of doing it - you can use parseFloat() to get the order number. This works since parseFloat returns all numerical values up to but not including the first non-numerical character ("?").
var urlStr = 'http://localhost/mywebsite/checkout/order-received/28564?key=wc_order_5b4dbc6b2f459';
var orderNumber = parseFloat(urlStr.split('order-received/')[1]);
console.log(orderNumber); //gives 28564
Because when you do orderResponseUrl.split("/"); it does NOT change orderResponseUrl, it creates a new array.
var parts = orderResponseUrl.split("/");
console.log(parts);
if the length is always same then you can use substring function.
var str = "Hello world!";
var res = str.substring(1, 4);
now res contain
console.log(res); // ell
if you do not know the index, you can find like this.
var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");
now n look like
console.log(n); // 13

How Do I Create a $_POST array from textarea input

Here is what I am trying to do.
I have a textarea input box, I would like to enter in data in an array format like this into that textarea box
'key1'='value1'
'key2'='value2'
'key3'='value3'
I then want to take this data and use it in my ajax call like so
var a = $("textarea#array_box").val().split('\n');
$.ajax({
url: 'index.php/controller/function',
type: "POST",
data: a,
success: function(data) {
console.log(data);
I am trying to get the data to pass in so that in the controller if i did one of the return statements below I would get the resulting output.
return $_POST['key1'] // should return 'value1'
return $_POST['key2'] // should return 'value2'
return $_POST['key3'] // should return 'value3'
How do I code this so that I can type into my textarea box an array, and pass that array into my controller as a $_POST?
based on your code, you can do something like this:
<?php
$tempvar=$_POST['data'];
$result = array();
foreach($tempvar as $tempitem){
$tempitem=str_replace("'","",$tempitem); //we get rid of the ' symbols
$t=explode("=",$tempitem); //' divide them by the "=" symbol
$result [$t[0]]=$t[1];
}
//the result variable now holds the array
echo $result['key1'] // value1
?>
You can use .filter(Boolean) to remove empty elements from a array; $.each() to iterate a array, .trim() to remove space characters, .replace() with RegExp /=(?=')/ to replace = with :; RegExp /'/g to replace ' with "; create a string to concatenate string at each iteration; JSON.stringify() following $.each(); pass result of JSON.stringify() to JSON.parse() as data to POST
$("button").click(function() {
var a = $("textarea#array_box").val().split("\n").filter(Boolean);
var textareaData = "";
$.each(a, function(key, value) {
textareaData += value.trim()
.replace(/=(?=')/, ":")
.replace(/'/g, '"')
+ (key < a.length - 1 ? "," : "");
});
textareaData = JSON.stringify("{" + textareaData + "}");
console.log(textareaData);
$.ajax({
url: "/echo/json/",
type: "POST",
data: JSON.parse(textareaData),
success: function(data) {
console.log(data);
}
});
});
jsfiddle https://jsfiddle.net/ahnegop3/3/
ajax data format must be {key:value,key,value} .So to getting that format , you need do a little loop with $.each and do assign key and value by like this
object[key] = value
var a = $("textarea#array_box").val().split('\n');
var temp = [];
$.each(a,function(i,v){
s = v.split("="); //split again with =
s[0] = s[0].replace(/'/g,""); //remove ' from string
s[1] = s[1].replace(/'/g,"");
temp.push(s[0],s[1]);
});
a = {};
//creating data objects
$.each(temp,function(i,v){
if(i % 2 == 0){
a[temp[i]] = temp[++i];
}
});

How to insert a json object into an unordered list

I have a json object that i created using obj = JSON.parse(data). "data" was recieved from a webserver. I know the object is correct because i can print single variables from it into a div or my list.
This is what is the json object is created from:
[{"name":"Staurikosaurus","group":"Saurischia","diet":"Carnivore","period":"Triassic"},{"name":"Diplodocus","group":"Saurischia","diet":"Herbivore","period":"Jurassic"},{"name":"Stegosaurus","group":"Ornithischia","diet":"Herbivore","period":"Jurassic"},{"name":"Tyrannosaurus","group":"Saurischia","diet":"Carnivore","period":"Cretaceous"}]
Literally all i want to do is put this into a to show up on a web page.
My current code:
function getJson(){$.get(MY URL, function(data) {
// String
//console.dir(data);
// Parse JSON
var obj = JSON.parse(data);
// JSON object
//console.dir(obj);
$('#myList').html("<li>"+obj[0].period+"</li><li>"+obj[2].period+"</li>");
//$('#myList').html("<li>obj[2].period</li>");
});
}
This successfully prints out the list with Triassic then Jurrasic.
I would prefer to do this in Jquery but javascript is okay.
Thank You.
You are not iterating through the list, just printing out the 0-th and 2nd element in the array. Try:
function getJson(){$.get(MY URL, function(data) {
// String
//console.dir(data);
// Parse JSON
var obj = JSON.parse(data);
// JSON object
//console.dir(obj);
var inner = '';
for(i=0; i < obj.length; i++) {
inner += "<li>"+obj[i].period+"</li>";
}
$('#myList').html(inner);
});
}
I'm sure there's a cleaner way using jQuery but that should work
If you're want to use the jQuery syntax, process like this:
var listElement = '';
$.each(obj, function(index, value) {
listElement += '<li>' + data[obj].period + '</li>';
})
$('#myList').html(listElement);

CSV to JSON using jquery

I have file in csv format:
info,value
"off to home","now"
"off to office","tomorrow"
I want json out of this using jquery but couldnt find any help.Isnt it possible to use jquery for this?
My intended output is :
{
"items": [
{
"info": "off to home",
"value": "now"
},
{
"info": "off to office",
"value": "tomorrow"
},
]
}
PFB the code which i implemented. but it is not working
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="csvjson.js"></script>
<script>
$.ajax("data.csv", {
success: function(data) {
var jsonobject = csvjson.csv2json(data);
alert(jsonobject);
},
error: function() {
alert("error")
}
});
</script>
</head>
<body>
</body>
</html>
Using jquery-csv, specifically the toObjects() method
$.ajax({
url: "data.csv",
async: false,
success: function (csvd) {
var items = $.csv.toObjects(csvd);
var jsonobject = JSON.stringify(items);
alert(jsonobject);
},
dataType: "text",
complete: function () {
// call a function on complete
}
});
Note: You'll need to import the jquery-csv library for this to work.
What this does is transform the CSV data into an array of objects.
Since the first line contains headers, jquery-csv knows to use those as the keys.
From there the data is transformed to JSON using stringify().
If you need a wrapper object, just create one and attach the data to it.
var wrapper = {};
wrapper.items = items;
alert(wrapper);
Disclaimer: I'm the author of jquery-csv
Useful link, I have found. Maybe help someone.
http://jsfiddle.net/sturtevant/AZFvQ/
function CSVToArray(strData, strDelimiter) {
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp((
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"), "gi");
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec(strData)) {
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[1];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter)) {
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push([]);
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[2]) {
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[2].replace(
new RegExp("\"\"", "g"), "\"");
} else {
// We found a non-quoted value.
var strMatchedValue = arrMatches[3];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[arrData.length - 1].push(strMatchedValue);
}
// Return the parsed data.
return (arrData);
}
function CSV2JSON(csv) {
var array = CSVToArray(csv);
var objArray = [];
for (var i = 1; i < array.length; i++) {
objArray[i - 1] = {};
for (var k = 0; k < array[0].length && k < array[i].length; k++) {
var key = array[0][k];
objArray[i - 1][key] = array[i][k]
}
}
var json = JSON.stringify(objArray);
var str = json.replace(/},/g, "},\r\n");
return str;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
You can use Alasql library. Alasql can load the data file from server, parse it and put the result to array of JSON objects.
This is the code:
<script src="alasql.min.js"></script>
<script>
alasql('SELECT * FROM CSV("items.csv",{headers:true})',[],function(res){
var data = {items:res};
});
</script>
If you want to modify data (for example, use only one column or filter), you can do it "on the fly".
Alasql understands the headers and use them for SELECT statement:
alasql('SELECT info FROM CSV("items.csv") WHERE value = "now"',[],function(res){
console.log(res);
});
I think jquery csv plugin will be helpful to convert your CSV to an array, then you can use jquery json.
BTW, you can use $.get() to read your CSV file from server.

jQuery AJAX, array not getting serialized

I'm trying to post a multidimensional array using jQuery. I have verified that immediately before sending the array, it contains the contents it is supposed to (by checking specific elements and alerting them).
However, when I send the request, it's sending this:
Array
(
[undefined] =>
)
Here's the whole thing...
var mainArray = new Array();
$(".list").each(function(){
var day = $(this).attr("id");
var order = 1;
$("#" + id + " li").each(function(){
var subArray = new Array();
var id = $(this).attr("id");
subArray["id"] = id;
subArray["order"] = order;
subArray["day"] = day;
mainArray.push(subArray);
order++;
});
});
// This displays what I would expect
alert(mainArray[0]['id']);
alert(mainArray[1]['id']);
alert(mainArray[2]['id']);
alert(mainArray[3]['id']);
// This doesn't work
$.ajax({
type: 'post',
url: 'test2.php',
data: mainArray,
success: function(data) {
$("#test").html(data);
}
});
Any ideas? My understanding is that jQuery is supposed to serialize the array automatically?
Your code is totally wrong!
At first, give your 2-dimensional array some name for example items (or whatever you want). Second, you can't use Array for creating hash (theoretically you can but it's bad and jQuery doesn't understand this), you have to use object literals {} instead of Array, use Array only with numeric keys (use literals [] for creating array instead of new Array). Your code:
var mainArray = [];
$(".list").each(function(){
var day = $(this).attr("id");
var order = 1;
$("#" + id + " li").each(function(){
var subArray = {};
subArray["id"] = $(this).attr("id");
subArray["order"] = order;
subArray["day"] = day;
mainArray.push(subArray);
order++;
});
});
$.ajax({
type: 'post',
url: 'test2.php',
data: { items: mainArray },
success: function(data) {
$("#test").html(data);
}
});
P.S.: you can use $.param (convert js objects into query string) to figure out your mistakes
Stringyfy the data before you send it to the server
Also it's a better practice to send the data as a Map..
Instead of this
data: mainArray,
Try
data: { 'arr': JSON.stringify(mainArray) },

Categories

Resources