Why can't I open() and parse() this JSON file in Javascript? - javascript

I am using Django to build a web serivce in Python and one of my tasks is to parse a .json file within my project.
The code compiles but the var json_data trying to hold the data becomes null when I try to access the json file.
<head>
<meta charset="UTF-8">
<title>Network Graph3</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<script>
// import json;
window.onload = function () {
var arr = [];
var json_data = open("{% static 'static/json/graphData.json' %}");
var obj = JSON.parse(json_data);
var i;
console.log(json_data)
if (obj == null){
return
}
for (i = 0; i < obj.documents; i++){
point = obj.documents[i];
arr[point.id].y = point.score;
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title:{
text: "Dialog Sentiment Analysis"
},
axisY:{
includeZero: false
},
data: [{
type: "line",
dataPoints: arr
// [
// { y: 450 },
// { y: 414},
// { y: 520, indexLabel: "highest",markerColor: "red", markerType: "triangle" },
// { y: 460 },
// { y: 450 },
// { y: 500 },
// { y: 480 },
// { y: 480 },
// { y: 410 , indexLabel: "lowest",markerColor: "DarkSlateGrey", markerType: "cross" },
// { y: 500 },
// { y: 480 },
// { y: 510 }
// ]
}]
});
chart.render();
}
</script>
</head>
The sample json data looks like:
{"documents": [{"id": "0", "score": 0.8365770578384399},
{"id": "2", "score": 0.9896875619888306},
{"id": "3", "score": 0.5},
{"id": "4", "score": 0.5},
{"id": "6", "score": 0.12722820043563843},
{"id": "7", "score": 0.16494140028953552},
{"id": "8", "score": 0.7551238536834717},
{"id": "9", "score": 0.12901419401168823},
{"id": "10", "score": 0.5},
{"id": "11", "score": 0.7559014558792114},

in javascript open() is for opening URL in new tab/window not reading the content, use XMLHttpRequest() or jQuery $.ajax() / .getJSON(). or you mean want to do python open() ?
code for javascript
window.onload = function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
// proccess json here
readJson(xhr.responseText);
}
}
xhr.open('GET', "/'static/json/graphData.json=", true);
xhr.send(null);
}
function readJson(json_data) {
var arr = [];
var obj = JSON.parse(json_data);
var i;
console.log(json_data)
....
....
}

So many issues here...
I'm assuming your code is expected to call the open() python function and on this case you cannot call it from javascript context as it will be evaluated to window.open() (which has nothing to do with python) rather than python function.
So all you have to do is read json file from view and return back to template context as serialized json string, something like this:
from django.shortcuts import render
def my_view(request):
context = {"data": None}
with open('data.json') as f:
context['data'] = json.load(f)
return render(request, 'templates/my_template.html', context)
Now just use JSON.parse().
Another option is rely on $.getJSON() if you are using jQuery or similar library or AJAX, fetching json data from server via HTTP (it requires json file has public access via HTTP).

Related

Chart js Loop Dataset

I'm very new to Chart js and JavaScript in general so am probably doing a few thing wrong here.
I am creating a scatter plot which depending on user input could have a variable number of values.
I was wondering if there's a way to use a for loop inside the datasets rather then how I currently have all the x and y values listed?
This is my current code.
const values = ["1", "2", "3", "4", "5", "6", "7", "8"];
const data = {
datasets: [
{
data: [
{
x: values.at(0),
y: values.at(1)
},
{
x: values.at(2),
y: values.at(3)
},
{
x: values.at(4),
y: values.at(5)
},
{
x: values.at(6),
y: values.at(7)
}
],
backgroundColor: "#55c4ec"
}
]
};
const myChart = new Chart(document.getElementById("myChart"), {
type: "scatter",
data: data
});

How to add external data to javascript for jquery auto complete

I'm trying to make a auto complete search bar using jquery autocomplete. The thing is I need to display Json data from an external site into my search bar.
Whenever I try to put the data as such from json into the script, it's working. But when I refer external url it refuses to work.
I tried implementing all json data into my script. But it takes so long to process as there will be more than 40000+ lines in my html page.
The Json link for the data which I have to display is here
<script>
$('#id_ticker').autocomplete({
source: function(request, response) {
var data = {
"success": true,
"data": [
{
"symbol": "AACG",
"name": "ATA Creativity Global American Depositary Shares",
"lastsale": "$2.19",
"netchange": "-0.45",
"pctchange": "-17.045%",
"volume": "1408435",
"marketCap": "68715455.00",
"country": "China",
"ipoyear": "",
"industry": "Service to the Health Industry",
"sector": "Miscellaneous",
"url": "/market-activity/stocks/aacg"
},
{
"symbol": "AACI",
"name": "Armada Acquisition Corp. I Common Stock",
"lastsale": "$9.88",
"netchange": "0.01",
"pctchange": "0.101%",
"volume": "8345",
"marketCap": "204609860.00",
"country": "United States",
"ipoyear": "2021",
"industry": "",
"sector": "",
"url": "/market-activity/stocks/aaci"
}],
"additional_data": {
"pagination": {
"start": 0,
"limit": 5,
"more_items_in_collection": true,
"next_start": 5
}
}
};
var datamap = data.data.map(function(i) {
return {
label: i.symbol + ' - ' + i.name.split(' ').slice(0, 2).join(' '),
value: i.symbol,
desc: i.title
}
});
var key = request.term;
datamap = datamap.filter(function(i) {
return i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0;
});
response(datamap);
},
minLength: 1,
delay: 500
});
</script>
The above code works and the below code doesn't.
<script>
$('#id_ticker').autocomplete({
source: function(request, response) {
var data = {
"success": true,
"data": ["https://raw.githubusercontent.com/rreichel3/US-Stock-Symbols/main/nyse/nyse_full_tickers.json"
],
"additional_data": {
"pagination": {
"start": 0,
"limit": 5,
"more_items_in_collection": true,
"next_start": 5
}
}
};
var datamap = data.data.map(function(i) {
return {
label: i.symbol + ' - ' + i.name.split(' ').slice(0, 2).join(' '),
value: i.symbol,
desc: i.title
}
});
var key = request.term;
datamap = datamap.filter(function(i) {
return i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0;
});
response(datamap);
},
minLength: 1,
delay: 500
});
</script>
Looking for a solution to add this and also for a solution to reduce the json key pair with only "symbol" and "name" from each corresponding data in the link.
Try this:
function toAutocomplete(dt, keyvar){
let rli = [];
for (let i = 0; i < dt.length; i++) rli.push(dt[i][keyvar]);
return rli;
}
function inArrayAutocompleteSelected(key, array_autocomplete, array_master){
let x = array_master[$.inArray(key, array_autocomplete)];
return x;
}
$('#id_ticker').autocomplete({ source: [], minLength: 1 });
// $('#id_ticker').autocomplete("disable");
let url = 'https://raw.githubusercontent.com/rreichel3/US-Stock-Symbols/main/nyse/nyse_full_tickers.json';
let r = _ajax('GET', url, ''); // your ajax script
console.log(r);
let liAuto = toAutocomplete(r, 'name');
console.log(liAuto);
$('#id_ticker').autocomplete("option", "source", liAuto );
// $('#id_ticker').autocomplete("enable");
$("#id_ticker").autocomplete({
select: function( event, ui ) {
console.log(ui, ui.item);
getData = inArrayAutocompleteSelected(ui.item.value, liAuto, r);
console.log(getData);
}
});

Tableau json API WebConnector

I've written the following tableau webconnector to pull data from an internal API, using earthquakeUSGS.html as a guideline (https://github.com/tableau/webdataconnector). The API returns json (see code below). I've been using the "Web data connector simulator 2.0" and all has been going well. I get the correct Table, however, Im unable to "Fetch Table Data". As this is my first js script, Im very sure that is were the error is. To iterate through the data I used the answer from Korijn in this post Iterate through nested json object array
The Problem: Is probably with the js iterator over the json object. If anyone can take a look at the json (below), and have a look at my iterator, I would greatly appreciate it. This is what makes it impossible for me to fetch data.
test.js
(function() {
// Create the connector object
var myConnector = tableau.makeConnector();
// Define the schema
myConnector.getSchema = function(schemaCallback) {
var cols = [{
id: "prog",
alias: "PrognosisTime",
dataType: tableau.dataTypeEnum.string
}, {
id: "start",
alias: "Start",
dataType: tableau.dataTypeEnum.date
}, {
id: "val",
alias: "Value",
dataType: tableau.dataTypeEnum.float
}];
var tableSchema = {
id: "table",
alias: "187",
columns: cols
};
schemaCallback([tableSchema]);
};
// Download the data
myConnector.getData = function(table, doneCallback) {
$.getJSON("http://myapi.com/119%2C7777/Flattened?start=today&end=today&timeZone=CET&asOf=now&aggregation=None", function(resp) {
var feat = resp.features,
tableData = [];
tableData.push(
{"table":feat.properties.table}
);
// Iterate over the JSON object
//var SeriesId = feat.SeriesId
for(var i = 0; i <feat.DataPoints.length; i++){
var PrognosisTime = feat.DataPoints.PrognosisTime;
var Start = feat.DataPoints.Start;
var Value = feat.DataPoints.Value;
}
table.appendRows(tableData);
doneCallback();
});
};
tableau.registerConnector(myConnector);
// Create event listeners for when the user submits the form
$(document).ready(function() {
$("#submitButton").click(function() {
tableau.connectionName = "Neas"; // This will be the data source name in Tableau
tableau.submit(); // This sends the connector object to Tableau
});
});
})();
json from API
[
{
"SeriesId": 119,
"DataPoints": [
{
"PrognosisTime": null,
"Start": "2016-08-24T00:00:00",
"Value": 26.19
},
{
"PrognosisTime": null,
"Start": "2016-08-24T01:00:00",
"Value": 23.9
},
{
"PrognosisTime": null,
"Start": "2016-08-24T02:00:00",
"Value": 22.82
}
]
},
{
"SeriesId": 7777,
"DataPoints": [
{
"PrognosisTime": null,
"Start": "2016-08-24T00:00:00",
"Value": 36.39
},
{
"PrognosisTime": null,
"Start": "2016-08-24T00:15:00",
"Value": 28.81
},
{
"PrognosisTime": null,
"Start": "2016-08-24T00:30:00",
"Value": 24.28
}
]
}
]
The problem is this line:
var feat = resp.features
resp is an array from your JSON, there is nothing called features. So, simply iterate over resp (or feat = resp) and pull out your DataPoints array.

Angular services - multiple queries and summing

I have 1 API/projects that returns a JSON with
[
{
"id":100,
"name":"some name",
"x": "y"
},
{
"id":200,
"another name",
"x": "z"
}
]
I then have another API/costs call that returns something similar to:
[
{
"projectid":100,
"cost":300
},
{
"projectid":100,
"cost":100
},
{
"projectid":200,
"cost":500
}
]
I currently wrote a mess of ajax/jquery/JS code that builds a JS object with "id", "name", and the summed "cost". And I simply stringify it to a JSON object.
However, the following queries were more complex and it seemed like an inefficient and near impossible way to do through raw JS so I switched to angular services as it would be easier to inject for the front-end team.
I'm not familiar with angular at all, and I only have a simple service that queries all the projects or 1 project given the ID.
Is it possible in Angular to query the API and build a JSON that takes only the name and id from the first query, and sums the cost for the appropriate project in the second query and returns a JSON with:
[
{
"id":100,
"name":"some name",
"cost":400
}
]
[
{
"id":200,
"name":"another name",
"cost":200
}
]
Thanks
This is a solution with plain Javascript and linear complexity.
var project = [{ "id": 100, "name": "some name", "x": "y" }, { "id": 200, name: "another name", "x": "z" }],
cost = [{ "projectid": 100, "cost": 300 }, { "projectid": 100, "cost": 100 }, { "projectid": 200, "cost": 500 }],
merged = function (p, c) {
var o = {},
r = p.map(function (a) {
o[a.id] = { id: a.id, name: a.name, cost: 0 };
return o[a.id];
});
c.forEach(function (a) {
o[a.projectid].cost += a.cost;
});
return r;
}(project, cost);
document.write('<pre>' + JSON.stringify(merged, 0, 4) + '</pre>');
Some pseudo-code:
var projects = null;
$http.get('API/projects').then(function(response) {
projects = JSON.parse(response.data);
$http.get('API/costs').then(function(response) {
var costs = JSON.parse(response.data);
projects.forEach(function(project) {
var sum = 0;
costs.forEach(function(cost) {
if (project.id === cost.projectid) {
sum += cost.cost;
}
});
project.cost = sum;
});
};
});
console.log(projects);
Should work with some tweaking.
Could be much more elegant though...

JSon with HighCharts and ASP.NET

I'm new using highcharts and JSON.
My javascript code is this:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'grafica',
type: 'spline'
},
series: [{}]
};
$.getJSON('ajax/gettipomov.aspx', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
And the data returned by the server and received by JavaScript is this:
[{"tipoMov":"Ajuste negativo","valorTipoMov":5},{"tipoMov":"Ajuste positivo","valorTipoMov":5},{"tipoMov":"Compra","valorTipoMov":5}, {"tipoMov":"Transferencia","valorTipoMov":5},{"tipoMov":"Venta","valorTipoMov":5}]
The problem is that chart is not showing any data, the chart is blank: image
The JSON Encoding that I use is:
var encoder = new JavaScriptSerializer();
return encoder.Serialize(obj);
That's the format expected:
{ "name": "Ajuste negativo", "y": 5 },
{ "name": "Ajuste positivo", "y": 5 },
{ "name": "Compra", "y": 5},
{ "name": "Transferencia", "y": 5},
{ "name": "Venta", "y": 5}
tipoMov and valorTipoMov mean nothing to Highcharts, so change your Object to return the properties named accordingly.

Categories

Resources