How to decode CSV to Array? Javascript - javascript

How to convert this CSV object to array or JSON .
Thanks
var obj = 3;ID;NAME;

You shouldn't really be rolling your own code to parse csv unless the format is very simple. You're going to end up with a massive amount of extra work to handle all the special cases that will arise.
You can use jQuery and jquery-csv:
Include the scripts:
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//jquery-csv.googlecode.com/files/jquery.csv-0.71.min.js"></script>
Decode like this:
var csv = "heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2";
jsObject = $.csv.toObjects(csv)
Example in this plnkr: http://plnkr.co/edit/xS1IRNwNCwvLBKzpliBU?p=preview

If you want to split a comma delimited string into an array you can do it as such:
var csv = "a,string,seperated,by,comma"
var array = csv.split(",");

It needs to be a string, and then you can use the split function, as in:
var array= "3;ID;NAME".split(";");
See the MDN. Note you can split on any character, semicolon (as you have above), or if true CSV, a comma too.

my answer.
Thanks.
var obj = 3;ID;NAME;
var myArr = obj.split(';');
document.writeln(myArr[0]); //result "3"
document.writeln(myArr[1]); //result "ID"
document.writeln(myArr[2]); //result "NAME"

Related

How to make javascript turn a multidimensional array into a string?

I have a multidimensional array in javascript that I would like to be able to turn into a string while preserving brackets. I have taken a look at other questions such as javascript - Convert array to string while preserving brackets and the answers there didn't help me much.
My array could look like the following:
[[[0,0,1],1],[[1,0,0],4],[[1,0,1],5], [[0,1,1],3],[[1,1,0],6],[[0,1,0],2]]
When I print the array I see:
0,0,1,1,1,0,0,4,1,0,1,5,0,1,1,3,1,1,0,6,0,1,0,2
The output that I am expecting is what the original array looks like.
I have also tried the following code:
alert("[[" + myArray.join("],[") + "]]");
This works for almost everything, I get an output of:
[[0,0,1,1],[1,0,0,4],[1,0,1,5], ...
And I would like to see what the origional array looks like with the brackets. I would also like to stay away from JSON.stringify(); and JSON.parse();
JSON.stringify() and JSON.parse() will do exactly what you ask for. Try it out:
var arr = [[[0,0,1],1],[[1,0,0],4],[[1,0,1],5], [[0,1,1],3],[[1,1,0],6],[[0,1,0],2]];
var str = JSON.stringify(arr);
alert(str);
var parsed = JSON.parse(str);
alert(parsed);
console.log(parsed);

Expect Object but get String when parsing JSON

I am trying to parse a simple JSON string using jQuery
var parsedJSON = $.parseJSON('{"graph_data": "{}"}');
I would expect typeof(parsedJSON.graph_data) to be an Object but instead it is returning string. What is the correct way to return an Object?
It should be like
var parsedJSON = $.parseJSON('{"graph_data": {}}');
console.log(typeof(parsedJSON.graph_data));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
no need of " for object, " is needed for defining string and object key. So it will treat as string here. For more about JSON structure and example visit http://www.json.org/.
try it.
var parsedJSON = $.parseJSON('{"graph_data": "{}"}');
console.log(parsedJSON.graph_data);

Parse JSON array in JavaScript into several Variables

I have a JSON string below that is being stored as a var in JavaScript. I am trying to parse the pieces of the string into variables.
In particular, I need the address, postcode, region, and locality.
This JSON array is being stored as a JS var called "data"
Does anyone know how I can begin parsing out those things? Thank you all!
[{"address":"2801 Elliott Ave","category_ids":[347],"category_labels":[["Social","Food and
Dining","Restaurants"]],"country":"us","email":"kimd#thedussingroup.com","factual_id":"43cfe23
8-ae8e-469a-8592-a1edc8603051","fax":"(206) 448-
9252","latitude":47.615154,"locality":"Seattle","longitude":-122.353724,"name":"The Old
Spaghetti Factory","neighborhood":["Belltown","Downtown","Downtown
Seattle"],"postcode":"98121","region":"WA","tel":"(206) 441-
7724","website":"http:\/\/www.osf.com"}]
Appreciate the help!
You JSON is an array (since it's contained in [ and ]), so you need:
var data = JSON.parse('[{"addre....}]');
var address = data[0].address,
postcode = data[0].postcode;
and so on...
for(var i in data[0]){
window[i] = data[0][i];
}
alert(address);
You can do this using JSON.parse
var data= your json;
JSON.parse(data);
Update:
In your case you don'e even need to parse you can use directly like
console.log(data[0].address); //returns 2801 Elliott Ave
console.log(data[0].category_ids); //returns [347]
Check this JSFiddle

Good way to serialize a list? - Javascript/AJAX

just felt like asking this as there are always jewels popping up on stackoverflow :)
What I have is the following list:
list1 = [['command','arg1','arg2'], ['command2','arg1'], ... ]
How would you recommend to transform it into a string in order to be passed as ONE GET argument?
e.g.
http://webgame_site.com/command_list/?data=...
What I am currently doing is separating lists using commas , ; , but I don't like this idea as the method would break if I decide to introduce these within strings.
I'm trying to be as compact as possible.
One idea I've had is to encode the list into base64:
[['command','arg1','arg2'], ['command2','arg1']]
=> "W1snY29tbWFuZCcsJ2FyZzEnLCdhcmcyJ10sWydjb21tYW5kMicsJ2FyZzEnXV0="
which is shorter than URIencode
Any ideas? :)
Convert it to json then encode the characters using encodeURI.
var list1 = [['command','arg1','arg2'], ['command2','arg1']];
var encoded = encodeURI(JSON.stringify(list1));
alert(encoded);
Edit for base64:
var list1 = [['command','arg1','arg2'], ['command2','arg1']];
var encoded = btoa(JSON.stringify(list1));
alert(encoded);
alert(atob(encoded));
jQuery.param() sounds good.

How do I separate a comma delimited variable into multiple variables?

This is probably very elementary, but I'm still learning.
I've imported a record from an XML file and have the result :
"a,b,c,d,e,f,g,h"
I would like to end up with 8 separate variables, one for each comma delimited value.
What is the shortest way to code this using javascript?
if you .split() the list, you'll end up with a single array with 'n' number of elements. Not -exactly- 8 separate variables, but 8 elements that can be accessed individually.
var myList = "a,b,c,d,e,f,g,h";
var myArray = myList.split( ',' );
alert( myArray[ 4 ] );
use split()
js>s = "a,b,c,d,e,f,g,h"
a,b,c,d,e,f,g,h
js>a = s.split(',')
a,b,c,d,e,f,g,h
js>a[0]
a
js>a[4]
e
Use split().
In your case, xml_string.split(',');
If you have the result as a string, use the split method on it:
var myList = "a,b,c,d,e,f,g,h";
var myArray = myList.split(",");

Categories