How to load and print json array/object in javascript - javascript

I do not have any json and d3 knowledge (just started to read few hours back) but have very basic javascript knowledge. I have to load a json file and print all the array and objects on the console using d3. I was wondering if anyone can help me to solve it. Actually, I did it but does not work :(
My json file.
{
"addressfile": "info",
"struct": {
"address": [
[
"A",
"B",
],
[
"B",
"C",
],
],
"address1": {
"address2": {
"address3": {
"zip": [
"NUMBER",
0
]
},
"address_type": "Home"
},
}
},
"COUNTRY": {},
}
My javascript code...
<!DOCTYPE html>
<meta charset="utf-8">
<style>
<body>
<script>
//LOADING JSON FILE
d3.json("address.json", function(error, root) {
if (error) return console.error(error);
for (var p in location) if (location.hasOwnProperty(p)) {
console.log(p + " : " + location[p]);
}
}
</script>
</body>
</html>
Please help me to solve it...

Try
d3.json("appinfo.json", function(location) {
I know the docs say the callback takes two parameters, in a project I recently did with d3 version 3.4.13, the callback function would only work if I only passed it the data parameter.

your code missing a closing parenthesis - );
correct code would be :
<script>
d3.json("appinfo.json", function(error, root) {
if (error) return console.error(error);
console.log(root) // output -your JSON data as pojo
//for (var p in location) if (location.hasOwnProperty(p)) {
// console.log(p + " : " + location[p]);
//}
});
</script>
make sure you write correct url to your json file in first parameter to d3.json().
make sure that appinfo.json contain correct json object, you can test it at http://jsonlint.com/

Thanks everyone.. After struggling I got the solution..
Solution: External Json files are not supported by the browsers ..so I needed to use webserver. Then I was able to see the output of it in the console.
the final code:
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<script src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
<script>
d3.json("address.json", function(location) {
console.log(location)
});
</script>
</body>
</html>
Hope it might help others to solve in minutes not in hours like me.....

Related

PapaParse doesn't handle my date correctly

I am having an issue creating a chart with some JSON that papaparse gives me. It continually gives me this error.
c3.js:2100 Failed to parse x '10-18-2018' to Date object
I've attempted to change the date format in csv to no avail. I have followed examples from c3 website, papaparse examples, and some stack overflow questions. Hopefully someone can tell me what I'm doing wrong so I can move forward with my project. Here is the code and the csv lines
app.js
"use strict";
$(function () {
$.get("108jbdata.csv") // Use HTTP GET (via Live-server) to retreive data from the static CSV file that we have included with our web assets.
.then(function (response) {
// Callback is executed when data is asynchronously received.
var parseOptions = {
// Parse options given to PapaParse.
header: true, // Allow PapaParse to derive field names from the CSV header line.
dynamicTyping: true, // Tell PapaParse to parse CSV string fields to the correct types for us.
};
var parsed = Papa.parse(response, parseOptions); // Parse the CSV data retreived from Live-server.
console.log(parsed);
var chart = c3.generate({
// Generate our chart.
bindto: "#chart",
data: {
json: parsed.data, // Plug the parsed CSV data into the chart.
keys: {
x: "Date",
xFormat: "%m-%d-%Y",
value: [
"KFISH", // Specify which column from the CSV file that we want to appear in the chart.
"WATER",
],
},
},
axis: {
x: {
type: "timeseries",
tick: {
format: "%m-%d-%Y",
},
},
},
});
})
.catch(function (err) {
// Handle any error that might have occurred.
console.error(err);
});
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>C3 chart template</title>
<link href="bower_components/c3/c3.css" rel="stylesheet" />
</head>
<body>
<div id="chart"></div>
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/d3/d3.js"></script>
<script src="bower_components/c3/c3.js"></script>
<script src="bower_components/papaparse/papaparse.js"></script>
<script src="app.js"></script>
</body>
</html>
csv
Date,Iron,Chromium,Lead,Copper,Tin,Aluminum,Nickel,Silver,Silicon,boron,Sodium,Magnesium,Calcium,Barium,Phosphorous,Zinc,Molybdenum,Tin1,Vandium,W,Potassium,Antimony,Lithium,Maganese,Cadmium,VISC40,TAN,KFISH,WATER,PC0,PC1,pc2,pc3,pc4,pc5,PCISO0,PCISO1,PCISO2
"10-18-2018",0,0,3,0,0,0,0,0,2,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,65.03,0.37,15,0.0015,374,229,52,19,2,0,16,15,13
"11-2-2018",0,0,0,0,3,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,8,0,0,0,64.63,0.5,24,0.0024,2915,388,15,3,0,0,19,16,11
"11-29-2018",0,0,0,0,0,0,0,0,2,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,64.13,0.93,23,0.0023,3292,527,16,4,1,0,19,16,11
"12-13-2018",0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,63.95,0.91,20,0.002,3076,517,14,5,1,1,19,16,11
"1-14-2019",0,0,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64.74,0.84,13,0.0013,4007,698,32,9,1,0,19,17,12
I got past being unable to parse the string date from the csv as a Date by going through each element and parsing it as a Date before I sent it off to the generate function.
parsed.data.forEach((h) => {
h.Date = Date.parse(h.Date);
});

ml5 (ml5.js): How do I add my own data to the KNN classifier?

Trying to use the ml5 (ml5js.org) KNN classifier on a game I made. But I don't understand how to add my own data to it.
<!DOCTYPE html>
<html>
<head>
<title>Getting Started with ml5.js</title>
<script src="https://unpkg.com/ml5#0.1.3/dist/ml5.min.js"></script>
</head>
<body>
<script>
let grid = [
[1, 2],
[3, 4]
];
let knnClassifier = ml5.KNNClassifier();
console.log('trying to add to classifier');
addExample('left');
function addExample(label) {
knnClassifier.addExample(grid, label);
}
</script>
</body>
</html>
I expected that code to add to the classifier instead Im getting an error message:
"Uncaught TypeError: Cannot read property 'length' of undefined"
The ml5 page has a KNN classifier example where they convert their data in the following way.
// Convert poses results to a 2d array [[score0, x0, y0],...,[score16, x16, y16]]
const poseArray = poses[0].pose.keypoints.map(p => [p.score, p.position.x, p.position.y]);
Unsure but I think their data looks something like:
{
"score": 0.32371445304906,
"keypoints": [ { "position": { "x": 301.42237830162, "y": 177.69162777066 }, "score": 0.99799561500549 },...
]
}
Needed the last vertion, so change part of the link:
ml5#0.1.3
to
ml5#0.3.0
And it works.

How to export json object into excel using javascript or jquery?

I wanted to export my json object into excel file. I have searched in Google and tried the following, but I am unable to get or export my object data into excel file on clicking of button, it is downloading but without any columns/data(i.e empty file is downloading).
I am not sure what is the problem, Please someone help me regarding this. Thanks in advance !
Created Plnkr.
html:
<div id="dvjson"></div>
<br><button type="button" id='DLtoExcel'>
Download CSV
</button>
js:
$(document).ready(function(){
//if I give below json object, file is downloading with the columns/data and hence it is fine
//var testjsondata = [{"number":123}];
//if I give like below object, empty file is downloading, not having any data
//it is not working //it should also work
//var testjsondata = {"number": 123}//it is not working //it should also work
//and the following object format also should work
var testjsondata = {
"test": {
"name": "abc",
"address": [{
"number": "12345",
"street": "xyz"
}]
},
"mynumber": 12
};
var $btnDLtoExcel = $('#DLtoExcel');
$btnDLtoExcel.on('click', function () {
$("#dvjson").excelexportjs({
containerid: "dvjson"
, datatype: 'json'
, dataset: testjsondata
, columns: getColumns(testjsondata)
});
});
console.log(testjsondata);
});
Any other solutions or libraries also welcome, my json object is plain type, not any array type.

Dojo accessing a javascript object in external file

I am trying to access a simple javascript variable / object I defined in an external file. My question is how to load it by dojo. Here is my plunker code that didn't work:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial: Hello Dojo!</title>
</head>
<body>
<!-- load Dojo -->
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"
data-dojo-config="async: true"></script>
<script type="text/javascript">
require({
packages: [
{
name: 'myApp',
location: window.location.href.replace(/\/$/, "")
}]},
["dojo/dom", "myApp/config", "dojo/domReady!"], function(dom, config) {
console.log(config.keys);
});
</script>
</body>
</html>
config.js
var keys = {
"key_1": {
"your_name": "jimmy",
"your_msg": "hello world"
},
"key_2": {
"your_name": "billy",
"your_msg": "foo equals bar"
}
};
As you can see I tried to load the config.js file as config, and tried to access it as config in my code. I am getting undefined in the console.
I did some research and what I need to use looks like the dojo's define function so that config.js looks like this:
define({
keys : {
"key_1": {
"your_name": "jimmy",
"your_msg": "hello world"
},
"key_2": {
"your_name": "billy",
"your_msg": "foo equals bar"
}
}
})
You should define a module for your configuration file.
This can be achieved using the define passing as argument your object.
Basic example:
define({ yourProperty: yourValue});
More information can be found here: https://dojotoolkit.org/documentation/tutorials/1.10/modules/

Jstree: Loading json data asynchronously

I am currently trying to set up a Jstree, loading the data asynchronously from a webserver with the data provided in the json format. Before, I had the data stored in the html page itself, eg. by creating the <ul> </ul> structure. This worked well.
Then, following
http://agiliq.com/blog/2011/10/how-use-jstree/
I saved the data in the page as a Json string, which also worked fine. After that, I tried the asynchronous loading, where I encounter two problems:
When using Jstree jsTree 1.0-rc3 (as found in https://github.com/akshar-raaj/Using-jsTree), the tree structure is being built up correctly, but two expansion symbols appear left of each folder, which looks rather strange.
Then I tried to use the current version of Jstree, but this produces no tree at all and neither gives an error message.
Here is my html page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>Menu test</title>
<link rel="stylesheet" href="/static/jsTree/themes/default/style.min.css" />
<script src="/static/jquery-1.11.1.js"></script>
<!--<script src="/static/jsTree/jstree.js"></script>-->
<script src="/static/jsTree/jstree_v3.js"></script> <!-- Current Version -->
<script>
$(function() {
$.ajax({
async : true,
type : "GET",
url : "../test2.json",
dataType : "json",
success : function(json) {
createJSTrees(json);
},
error : function(xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
});
function createJSTrees(jsonData) {
$("#menuTree").jstree({
"json_data" : {
"data" : jsonData
},
"plugins" : [ "themes", "json_data", "ui" ]
});
}
</script>
</head>
<body>
Tree:
<div id="menuTree" >
</div>
</body>
</html>
And this is what test2.json gives out:
[ { "data" : "a", "children" :[ {"data":"b", "metadata":{"href":"b"}}, {"data":"c", "metadata":{"href":"c"}} ] } ]
Could you help me?
Thank you very much in advance!

Categories

Resources