convert json string to csv using javascript - javascript

I have seen some of the posts for converting json to csv
for example 'http://jsfiddle.net/FLR4v/'.
I could not make them to convert this json to csv .
Here is my code (this works well but does not work with commented out var json3 below)
<html>
<head>
<title>JSON to CSV</title>
<script src="json.js" type="text/javascript"></script>
<script type="text/javascript">
//var json3 = { "inp1:val1": { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ] ] }}
var json3 = { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ], ] }
DownloadJSON2CSV(json3.data);
function DownloadJSON2CSV(objArray)
{
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
line += array[i][index] + ',';
}
// Here is an example where you would wrap the values in double quotes
// for (var index in array[i]) {
// line += '"' + array[i][index] + '",';
// }
line.slice(0,line.Length-1);
str += line + '\r\n';
}
window.open( "data:text/csv;charset=utf-8," + escape(str))
}
</script>
</head>
<body>
<h1>This page does nothing....</h1>
</body>
</html>
The above code works ok.
What I need is the above needs to work with the below
var json3 = { "inp1:val1": { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ] ] }}
Thanks for your help

You still haven't explained clearly what your desired output is ("CSV" is too vague, especially when your original jsfiddle produced semicolon separated output).
But you do seem to be saying that your code works if you take this object:
var json3 = { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ], ] }
...as input to your function as follows:
DownloadJSON2CSV(json3.data);
But now you want to deal with an input object that has a slightly different structure, essentially the same thing but with an extra "wrapping" layer around your original structure:
var json3 = { "inp1:val1": { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ] ] }}
If I've summed up your question accurately, here's what you need:
DownloadJSON2CSV(json3["inp1:val1"].data);
This calls your function passing the array of arrays referenced by the "data" property of the object referenced by the "inp1:val1" property of the outermost object.
(Note that what you are calling "json" is not json at all, it is an object that happens to be created using JS's object literal syntax.)
Homework for you: read the MDN article Working With Objects.

Related

Parse ipstack JSON Data using JS

I was working on how to extract data from JSON data
I wrote the below code to extract the variable named code that is equal to ur
But not getting the results.
<script>
var txt = '{ "type":"ipv4", "location":{ "geoname_id":2816, "languages":[ { "code":"en", "name":"English" }, { "code":"ur", "name":"Urdu" } ], "is_eu":false } }';
var obj = JSON.parse(txt);
console.log(obj.location.languages.code);
</script>
obj.location.languages is an Array, you cannot access code property be requesting it directly on it. code property of which item it should give you back after all, one of English or Urdu? You will need to use an index of the item (starts with 0) to access it, or use one of the iterator methods on the Array, like forEach(), map() or reduce() to cycle trhough all of them. Here's an example:
var txt = '{ "type":"ipv4", "location":{ "geoname_id":2816, "languages":[ { "code":"en", "name":"English" }, { "code":"ur", "name":"Urdu" } ], "is_eu":false } }';
var obj = JSON.parse(txt);
var html = '';
obj.location.languages.forEach(function(lang) {
html += '<li>' + lang.name + ' (' + lang.code + ')</li>';
});
document.getElementById('languages').innerHTML = html;
Languages: <br />
<ul id="languages"></ul>
You must use index after languages propert. Because this propert type is array.
<script>
var txt = '{ "type":"ipv4", "location":{ "geoname_id":2816, "languages":[ { "code":"en", "name":"English" }, { "code":"ur", "name":"Urdu" } ], "is_eu":false } }';
var obj = JSON.parse(txt);
document.write(obj.location.languages[0].code);
</script>
Below code will get you all language code as an array.
<script>
var txt = '{ "type":"ipv4", "location":{ "geoname_id":2816, "languages":[ {"code":"en", "name":"English" }, { "code":"ur", "name":"Urdu" } ], "is_eu":false } }';
var obj = JSON.parse(txt);
document.write(obj.location.languages.map((language,i)=>language.code));
</script>
languages is an array, so try something like that:
obj.location.languages[0].code

Javascript turns array into string

I'm rewriting some Python code in javascript and I'm running into something strange. I'm sure I'm overlooking something stupid, but it appears that it's returning a comma-separated string where I expect an array.
python:
triples = [('one', 'two', 'three'), (...), ... ]
for w1, w2, w3 in triples:
key = (w1, w2)
if key in self.cache:
self.cache[key].append(w3)
else:
self.cache[key] = [w3]
returns:
('of', 'Thee,'): ['Sailing', 'Light'],
('meat', 'within'): ['is'],
javascript:
for (var i=0; i<=triples.length; i++) {
if (triples[i]) {
var key = [triples[i][0], triples[i][1]];
if (key in this.cache) {
this.cache[key].push(triples[i][2]);
} else {
this.cache[key] = [];
this.cache[key].push(triples[i][2]);
}
}
}
returns:
'you,estimated,': [ 'and', 'and' ],
'estimated,,and': [ 'far', 'far' ],

Having trouble matching users input to a .json file, keep getting "Uncaught ReferenceError: myExp is not defined"

I keep getting an error when I try to match users input data to a .json file. Here is my .js:
$.getJSON('rote.json', function(data){
var random = data.eats[Math.floor(Math.random() * data.eats.length)];
var title = random[0].cat;
var titleLength = random[0].cat.length;
$("h2").html(title);
var output = '';
$.each(random, function(key,val){
var snippedFieldLength = random.length - 1;
output += '<input type="search" name="search" class="search" placeholder="write your tag here" /><br><br>';
});
$('.fields').html(output);
$('.search').keyup(function(){
var searchField = $('.search:eq(1)').val();
var myExp = new RegExp(searchField, "i");
console.log(myExp);
var output2 = '';
$.each(random, function(key,val){
console.dir(val);
if (val.search(myExp) != -1) {
output2 += 'hello';
}
});
$('#update').html(output2);
});
});
Here is my .json file:
{"eats":
[
[
{"cat":"drinks"},
"soda",
"milk"
],
[
{"cat":"food"},
"burgers",
"fries",
"pizza"
]
]
}
I'm trying to match data I'm getting from a .json file to text inserted into html input fields generated using a loop. All of this is done with .json and jquery. I have no trouble randomly selecting items from my json category 'eats' and I have no trouble spontaneously creating fields that conform the the length of the categories (minus 1, since the 'cat' items should be excluded), but my problem is that I can't seem to get the regular expression to match the text the user will enter to the .json file. Does anybody have any ideas? I keep getting a "Uncaught ReferenceError: myExp is not defined" error.
The error I get when I run your code is that undefined is not a function. When you loop over random, the first value is the object { cat: "categoryname" }, and when you call val.search(myExp) it gets an error because that object doesn't have a .search method. The solution is to test whether the element is a string before trying to match it. Or you could use $.each(random.slice(1), function() { ...}) to skip over the first element.
function processJson(data){
var random = data.eats[Math.floor(Math.random() * data.eats.length)];
var title = random[0].cat;
var titleLength = random[0].cat.length;
$("h2").html(title);
var output = '';
$.each(random, function(key,val){
var snippedFieldLength = random.length - 1;
output += '<input type="search" name="search" class="search" placeholder="write your tag here" /><br><br>';
});
$('.fields').html(output);
$('.search').keyup(function(){
var searchField = $('.search:eq(1)').val();
var myExp = new RegExp(searchField, "i");
console.log(myExp);
var output2 = '';
$.each(random, function(key,val){
console.dir(val);
if (typeof val == "string" && val.search(myExp) != -1) {
output2 += 'hello';
}
});
$('#update').html(output2);
});
}
var myjson =
{"eats":
[
[
{"cat":"drinks"},
"soda",
"milk"
],
[
{"cat":"food"},
"burgers",
"fries",
"pizza"
]
]
};
processJson(myjson);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2></h2>
Fields:
<div class="fields"></div>
Update:
<div id="update"></div>
The best solution would be to redesign your data structure. Arrays should be used for uniform data, objects should be used for heterogeneous data. So it's inappropriate to have the object in the same array as the strings. This is how I suggest you do it:
[
{ cat: "drinks",
members: [
"soda",
"milk"
]
},
{ cat: "food",
members: [
"burgers",
"fries",
"pizza"
]
}
]

IE 8 Array iteration

Hi I'm debugging my page for IE8 compat mode, and this script just doesn't like to work and crushes.
Basically it had to iterate through a 3D array, and add a local path to a variable. Well I could do it otherwise, but I'm just curious why the ** it never works...
Any suggestions are welcome :) Here's the code:
for(i=0;i<menu_items_p.length;i++)
for(j=0;j<menu_items_p[i].length;j++)
menu_items_p[i][j][1]='http://127.0.0.1/'+menu_items_p[i][j][1];
and the array looks something like this:
var menu_items_p =
[
[ //Products
['Health Care', 'products/health.php'],
['Aroma Therapy','products/scents.php'],
],
[ // Empty
],
[ //Test
['What ever', 'spirulina/about.php'],
]
]
The problem though is that it sometimes have empty values, and array.length triggers some error...
When used your original array declaration:
var menu_items_p =
[
[ //Products
['Health Care', 'products/health.php'],
['Aroma Therapy','products/scents.php'],
],
[ // Empty
],
[ //Test
['What ever', 'spirulina/about.php'],
]
]
error occurs in IE8 but not in IE9. Just remove two commas:
var menu_items_p =
[
[ //Products
['Health Care', 'products/health.php'],
['Aroma Therapy','products/scents.php'] // here comma removed
],
[ // Empty
],
[ //Test
['What ever', 'spirulina/about.php'] // here comma removed
]
]
and all must work fine.
Maybe your code could handle empty values this way:
for(var i = 0; i < menu_items_p.length; i++) {
// we skip the value if it is empty or an empty array
if(!menu_items_p[i] || !menu_items_p[i].length) continue;
for(var j = 0; j < menu_items_p[i].length; j++) {
// again, we skip the value if it is empty or an empty array
if(!menu_items_p[i][j] || !menu_items_p[i][j].length) continue;
menu_items_p[i][j][1] = 'http://127.0.0.1/' + menu_items_p[i][j][1];
}
}
AS suggested by Yoshi and ThiefMaster, I made it following, and this is what solved it:
for(var i=0;i<menu_items_p.length;i++)
if (menu_items_p[i] !== undefined)
for(var j=0;j<menu_items_p[i].length;j++)
if (menu_items_p[i][j] !== undefined)
menu_items_p[i][j][1]='http://127.0.0.1/'+menu_items_p[i][j][1];
Global vars replaced.
Check for undefined.
It's a pity they didn't answer in a formal way, so I would have to answer my self :)
Thanks everyone!

Use a JSON array with objects with javascript

I have a function that will get a JSON array with objects. In the function I will be able to loop through the array, access a property and use that property. Like this:
Variable that I will pass to the function will look like this:
[{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}]
function test(myJSON) {
// maybe parse my the JSON variable?
// and then I want to loop through it and access my IDs and my titles
}
Any suggestions how I can solve it?
This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:
var arrayOfObjects = [{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}];
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
// If property names are known beforehand, you can also just do e.g.
// alert(object.id + ',' + object.Title);
}
If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.
var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...
To learn more about JSON, check MDN web docs: Working with JSON
.
This is your dataArray:
[
{
"id":28,
"Title":"Sweden"
},
{
"id":56,
"Title":"USA"
},
{
"id":89,
"Title":"England"
}
]
Then parseJson can be used:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
By 'JSON array containing objects' I guess you mean a string containing JSON?
If so you can use the safe var myArray = JSON.parse(myJSON) method (either native or included using JSON2), or the usafe var myArray = eval("(" + myJSON + ")"). eval should normally be avoided, but if you are certain that the content is safe, then there is no problem.
After that you just iterate over the array as normal.
for (var i = 0; i < myArray.length; i++) {
alert(myArray[i].Title);
}
Your question feels a little incomplete, but I think what you're looking for is a way of making your JSON accessible to your code:
if you have the JSON string as above then you'd just need to do this
var jsonObj = eval('[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]');
then you can access these vars with something like jsonObj[0].id etc
Let me know if that's not what you were getting at and I'll try to help.
M
#Swapnil Godambe
It works for me if JSON.stringfy is removed.
That is:
$(jQuery.parseJSON(dataArray)).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td>No Id</td><td>Title</td></tr>");
for(var i=0;i<datas.length;i++){
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");
}
document.writeln("</table>");

Categories