Load external JSON file in PaperJS - javascript

I thought this would be really simple to do with:
project.importJSON('structures.json')
Unfortunately this gives me:
JSON Parse error: Unexpected identifier "structures"
This "structures" must come from the JSON file structures.json itself which looks like this:
{
"structures": [
{"name":"shed", "width": 4, "height": 3, "depth": 5},
{"name": "house", "width": 6, "height": 7, "depth": 5},
{"name": "factory", "width": 4, "height": 3.5, "depth": 6.5,
"depth_sub_1": 5.5,
"depth_sub_2": 4.5 }
]
}
Any ideas on how to make this work? I'd rather not use jQuery for this.
Edit
So it seems to me that using importJSON can only work when the JSON is an actual Paper object. The same error keeps on occurring.
What's the alternative? I want my external 'structural' data in what is basically a JavaScript file. Should I use the regular route for doing so?
My html looks something like this:
<head>
<script type="text/javascript" src="../../assets/javascript/paper-full.js"></script>
<script type="text/paperscript" src="I/a_view_on_my_structures.js" canvas="phase-I"></script>
</head>
<body>
<canvas id="phase-I" resize="true"></canvas>
</body>

You should stringify your data.
var structures = {
"structures": [
{"name":"shed", "width": 4, "height": 3, "depth": 5},
{"name": "house", "width": 6, "height": 7, "depth": 5},
{"name": "factory", "width": 4, "height": 3.5, "depth": 6.5,
"depth_sub_1": 5.5,
"depth_sub_2": 4.5 }
]
}
project.importJSON(JSON.stringify(structures))
if you json data is in a different file you should read that file first
This is how you read a file
synchronously
var client = new XMLHttpRequest();
client.open('GET', 'path/to/your/file', false);
client.onreadystatechange = function() {
//your data is in client.responseText
console.log(client.responseText);
}
client.send(null);
asynchronously
var client = new XMLHttpRequest();
client.open('GET', 'path/to/your/file');
client.onreadystatechange = function() {
//your data is in client.responseText
console.log(client.responseText);
}
client.send();
notice that when you do this, you don't need to stringify your data, because you read it as a text, so you just have to pass the client.responseText content to the importJSON function

Related

Is there a way to read <script> tag contents

I have a site in which there is a <script> with a JSON inside. With user script in Tampermonkey, I want to get that JSON to work with it later.
So I thought that I can get it with getElemntsByTagName("script"), but I couldn't figure out how to get string out of it.
How do you get a string from getElemntsByTagName("script"), like console.log does?
Is there an easier way to do so?
window.wpProQuizInitList = window.wpProQuizInitList || [];
window.wpProQuizInitList.push({
id: '#wpProQuiz_67',
init: {
quizId: 67,
mode: 2,
globalPoints: 76,
timelimit: 0,
resultsGrade: [0],
bo: 3,
qpp: 0,
catPoints: [76],
formPos: 0,
lbn: "\u0417\u0430\u0432\u0435\u0440\u0448\u0438\u0442\u0438 \u0442\u0435\u0441\u0442",
json: {
"2944": {
"type": "single",
"id": 2944,
"catId": 0,
"points": 1,
"correct": [0,0,1,0]
},
"2945": {
"type": "single",
"id": 2945,
"catId": 0,
"points": 1,
"correct": [0,1,0,0]
},
"2946": {
"type": "single",
"id": 2946,
"catId": 0,
"points": 1,
"correct": [0,0,1,0]
},
…
}
}
}
You can use document.querySelector to get the first <script> element; there is no need to obtain a live HTMLCollection to get one element. You can then read its textContent.
let value = document.querySelector('script').textContent;
getElementsByTagName("script") will return an HTMLCollection which contains a list of script tags. You can get the text of the first script tag like this:
getElementsByTagName("script")[0].innerText

How to pass a variable from c# into javascript for plotting in plotly.js

I am trying to pass X and Y data generated in c# into plotly.js that update every second (or as often as programmatically possible). How would I reference in javascript a variable like x and y located in the .json file or c#? Ultimately, the javascript piece should run plotly with x and y taken from the c# code (Or in c#, I can generate a .json file every second). Plotly allows for dynamic updating, so this should be possible if the variables can be passed. I have included my starting point below:
C# Code:
dataPoint.X = 0;
dataPoint.Y = retrieveVariable(MachineInfoService.Instance.machineInfo.plot, 0);
xstr = dataPoint.X.ToString();
ystr = dataPoint.Y.ToString();
for (i = 1; i < numdataPoints; i++)
{
dataPoint.X = i;
dataPoint.Y = retrieveVariable(MachineInfoService.Instance.machineInfo.plot, i);
xstr =xstr +", " +dataPoint.X.ToString();
ystr = ystr +", "+ dataPoint.Y.ToString();
Globals.PlotlyX = xstr;
Globals.PlotlyY = ystr;
graphData.Add(dataPoint);
}
webView.Navigate(new Uri("ms-appx-web:///Assets/index3.html"));
index3.html:
<html>
<head>
<!-- Plotly.js -->
<!----<script src="https://cdn.plot.ly/plotly-latest.min.js"></script> -->
<script src="plotly-latest.min.js"></script>
<script type="text/javascript" src="../Assets/xydata.json"></script>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<!-- Plotly chart will be drawn inside this DIV -->
<div id="graphDiv"></div>
<script>
jQuery.get('../Assets/xydata.json');
Plotly.newPlot('plotly-chart', data, layout);
</script>
</body>
</html>
xydata.json:
{
"data": [
{
"x": [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ],
"y": [ 0, 3, 6, 4, 5, 2, 3, 5, 4 ],
"type": "scatter",
"name": "Plot 1"
},
{
"x": [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ],
"y": [ 0, 4, 7, 8, 3, 6, 3, 3, 4 ],
"type": "scatter",
"name": "Plot 2"
},
{
"x": [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ],
"y": [ 0, 5, 3, 10, 5.33, 2.24, 4.4, 5.1, 7.2 ],
"type": "scatter",
"name": "Plot 3"
}
],
"layout": {
"showlegend": true,
"legend": { "orientation": "h" }
}
}
I wouldn't write to a file for each plot update. The cleanest way would probably be to use Newtonsoft's Json.NET which helps you convert .NET objects to JSON. If you don't want to use another library, you could also just manually format a String into valid JSON, but that may be much more complicated/error prone.
After having new plot data, call the function via C#, like this:
PlotyObject data = new PlotyObject()
webView.Document.InvokeScript("updatePlotWithNewData", {JsonConvert.SerializeObject(data)})
OR
webView.Document.InvokeScript("updatePlotWithNewData", {"{...manually formatted JSON...}"})
In your index3.html file, you could do something like this to accept new data and update the Ploty chart:
<script>
var plotlyData = {...}
var layout = { ... }
$(document).ready(function() {
Plotly.newPlot('plotly-chart', plotlyData, layout);
});
function updatePlotWithNewData(newData) {
plotlyData = JSON.parse(newData);
Plotly.redraw('plotly-chart');
}
</script>

Error in web worker using importScripts(defiant.min.js)

I'm trying to use defiant.js in a web worker, since I'm doing heavy computation in addition to the JSON.search.
However I keep getting a
Uncaught Error: Uncaught ReferenceError: Defiant is not defined
I created a simple example using part of the defiant demo code.
Does anyone know whether this is a defiant.js issue or am I just importing the script wrong?
Or is there another solution on how this can be done?
JS in main.html
var obj = {
"car": [
{"id": 10, "color": "silver", "name": "Volvo"},
{"id": 11, "color": "red", "name": "Saab"},
{"id": 12, "color": "red", "name": "Peugeot"},
{"id": 13, "color": "yellow", "name": "Porsche"}
],
"bike": [
{"id": 20, "color": "black", "name": "Cannondale"},
{"id": 21, "color": "red", "name": "Shimano"}
]
}
var worker = new Worker('defiantWW.js');
worker.addEventListener('message', function(e) {
console.log( e.data);
}, false);
worker.postMessage(obj);
web worker file
self.addEventListener('message', function(e) {
importScripts('defiant.min.js')
var obj=e.data;
var search = JSON.search(obj, '//car[color="yellow"]/name');
self.postMessage(search);
}, false);
EDIT
changing the position of importScripts() as suggested by dandavis in comments - but same result
web worker file v2
importScripts('defiant.min.js')
self.addEventListener('message', function(e) {
var obj=e.data;
var search = JSON.search(obj, '//car[color="yellow"]/name');
self.postMessage(search);
}, false);
Sadly enough defiantJS does not support the use within a web-worker.
Got feedback from Hakan Bilgin on the issue:
There is already support for web workers in Defiant.js
<script src="defiant.min.js"></script>
<script>
var obj = {
"car": [
{"id": 10, "color": "silver", "name": "Volvo"},
{"id": 11, "color": "red", "name": "Saab"},
{"id": 12, "color": "red", "name": "Peugeot"},
{"id": 13, "color": "yellow", "name": "Porsche"}
],
"bike": [
{"id": 20, "color": "black", "name": "Cannondale"},
{"id": 21, "color": "red", "name": "Shimano"}
]
};
Defiant.getSnapshot(obj, function(snapshot) {
var found = JSON.search(snapshot, '//car');
console.log(found);
});
</script>
[Snapshot] doesn't give me access to defiant from within my own web-worker.
I can execute the Snapshot in the main thread and then post the result to my web-worker, however the large JSON (5-15mb) is handled only in the web-worker. I would have to pass it over to the main thread, run the Snapshot (which is executed in another web-worker) and then pass the result back to my WW.
Since I'm using the JSON.search quite often that would induce a lot of unnecessary overhead on the main thread.
No...you can not access Defiant from within a web worker
hi to load a service worker try this link:
https://developers.google.com/web/fundamentals/primers/service-workers
as it mentioned:
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}

How merge two objects array in angularjs?

I want to append following object array with existing one in angulajs for implementing load more feature.
ie,appending AJAX response with existing one each time.
I have one variable, $scope.actions which contains following JSON data,
{
"total": 13,
"per_page": 2,
"current_page": 1,
"last_page": 7,
"next_page_url": "http://invoice.local/activities/?page=2",
"prev_page_url": null,
"from": 1,
"to": 2,
"data": [
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
},
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
}
]
}
I want to append following JSON response each time this variable.
{
"data": [
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
},
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
}
]
}
I have tried with $scope.actions.data.concat(data.data);
but it is not working and getting following error message
$scope.actions.data.concat is not a function
You can use angular.extend(dest, src1, src2,...);
In your case it would be :
angular.extend($scope.actions.data, data);
See documentation here :
https://docs.angularjs.org/api/ng/function/angular.extend
Otherwise, if you only get new values from the server, you can do the following
for (var i=0; i<data.length; i++){
$scope.actions.data.push(data[i]);
}
This works for me :
$scope.array1 = $scope.array1.concat(array2)
In your case it would be :
$scope.actions.data = $scope.actions.data.concat(data)
$scope.actions.data.concat is not a function
same problem with me but i solve the problem by
$scope.actions.data = [].concat($scope.actions.data , data)
Simple
var a=[{a:4}], b=[{b:5}]
angular.merge(a,b) // [{a:4, b:5}]
Tested on angular 1.4.1

System Can't Find JSON file

I have a simple program I am writing that has 3 files:
1.an HTML file (index.html)
2.a Javascript file (app.js)
3.a JSON dataset (dataset.json)
All I want to do is get the browser to recognize the data and I can't do it.
My app.js file:
$(document).ready(function(){
$.getJSON('dataset.json', function(data){
console.log(data);
});
});
My dataset.json file:
[
{
"Gender": "Female",
"Height": 5'2,
"Weight": 100,
"Age": 25,
"Occupation": "Lawyer"
},
{
"Gender": "Male",
"Height": 5'9,
"Weight": 150,
"Age": 23,
"Occupation": "Student"
}
]
Any ideas? Am I missing something completely? On my index.html, all I have in the head is:
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
You JSON file is invalid
"Height": 5'2, <-- that is not valid
"Height": 5'9, <-- that is not valid
Needs to be a string or a number
"Height": "5'2",
"Height": "5'9",
You have to open it with a live server, otherwise it won’t work (opening the index.html for example). You can use a VSCode Plugin (LiveServer) for that.

Categories

Resources