Reading a JSON File using JQUERY within an HTA Application - javascript

So I have this HTA Application I'm working on, Which will be used in remote locations where there will be little to no internet. Its should be very basic as in I just want it to load/read a json file and edit/append some fields within the JSON file. If I load it within a web browser by changing the extention to .html it works and reads the json no problem, when I rename it back to .hta and execute its just blank. I dont understand why.
testJSON.hta
<html>
<head>
<title>TEST - JSON Editor</title>
<HTA:APPLICATION ID="oHTA" APPLICATIONNAME="TESTJSON" BORDER="thin" BORDERSTYLE="normal" CAPTION="yes"
ICON="TESTJSON/images/TEST_twit_logo_ijM_icon.ico" MAXIMIZEBUTTON="yes" MINIMIZEBUTTON="yes" SYSMENU="yes"
SCROLL="no" NAVIGABLE="yes" SINGLEINSTANCE="no" SHOWINTASKBAR="yes" VERSION="1.0" WINDOWSTATE="normal">
<script>
window.location = 'testJSON.html';
</script>
</head>
</html>
testJSON.html
<!DOCTYPE html>
<html>
<head>
<title>TEST - JSON Editor</title>
<meta http-equiv="x-ua-compatible" content="IE=edge" />
<link rel="stylesheet" href="TESTJSON/css/bootstrap.min.css">
<link rel="stylesheet" href="TESTJSON/css/style.css">
<script src="TESTJSON/js/jquery.min.js"></script>
<script src="TESTJSON/js/bootstrap.min.js"></script>
<!--Begin Vbscript-->
<script language="VBScript">
</script>
</head>
<body onload="readJSON()" scroll="no">
<div class="logo">
<img class="logo-image" src="TESTJSON/images/TEST-logo.png">
</div>
<div class="container">
<div class="row">
Select a JSON file: <input type="file" accept=".json" name="jsonFile"><br><br>
</div>
</div>
<div class="status_window">
Status / Information:
<div class="status_window_text" id="output">
</div>
</div>
</body>
<!--Begin Jscript-->
<script type="text/javascript">
function readJSON() {
$(document).ready(function () {
$.getJSON("example_2.json", function (data) {
var content = '<h3>' + data.quiz.sport.q1.question + '</h3>';
$(content).appendTo("#output");
});
});
}
function myFunction() {
alert("Page is loaded");
}
</script>
</html>
example_2.json
{
"quiz": {
"sport": {
"q1": {
"question": "Which one is correct team name in NBA?",
"options": [
"New York Bulls",
"Los Angeles Kings",
"Golden State Warriros",
"Huston Rocket"
],
"answer": "Huston Rocket"
}
},
"maths": {
"q1": {
"question": "5 + 7 = ?",
"options": [
"10",
"11",
"12",
"13"
],
"answer": "12"
},
"q2": {
"question": "12 - 8 = ?",
"options": [
"1",
"2",
"3",
"4"
],
"answer": "4"
}
}
}
}

Using HTML5 FILE API I was able to get the script working with the code below
This is the query from the JSON I was able to return.
JsonObj.quiz.sport.q1.question
Code:
function readJSON() {
//Testing to see if the text would display in the DIV
document.getElementById("output").innerHTML = "Importing JSON....";
//script start
JsonObj = null
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
f = files[0];
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
return function (e) {
// Render thumbnail.
JsonObj = JSON.parse(e.target.result);
console.log(JsonObj);
document.getElementById('output').innerHTML += '<ul>' + JsonObj.quiz.sport.q1.question + '</ul>';
};
})(f);
// Read in the image file as a data URL.
reader.readAsText(f);
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
}

Related

How to pass json file name to javascript function on button click?

I have a Javascript file that returns some HTML Content based on the content of a json file. In other words, in my file called "Resources" I have multiple json files and a single HTML File that contains multiple buttons. It can be more clear with an example, here is the HTML file:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="cards">
<div class="card">
<img src="first.jpg" class="card_image">
<a href="javascript:showMenu()" class="animated-button"> <!--showMenu() is inside menu-card.js-->
<span></span>
<span></span>
<span></span>
<span></span>
<p>FIRST BUTTON</p>
</a>
</div>
<div class="card">
<img src="second.jpg" class="card_image">
<a href="javascript:showMenu()" class="animated-button"> <!--showMenu() is inside menu-card.js-->
<span></span>
<span></span>
<span></span>
<span></span>
<p>SECOND BUTTON</p>
</a>
</div>
</div>
<script type="text/javascript" src="first.json"></script>
<script type="text/javascript" src="second.json"></script>
<script type="text/javascript" src="menu_card.js"></script>
</body>
</html>
Here is first.json :
products =
`[
{
"name": "Shoes",
"description": "This are some shoes.",
"price": "180"
}
]`;
Here is second.json :
products =
`[
{
"name": "Hoodies",
"description": "This are some hoodies.",
"price": "90"
}
]`;
Finally, here is menu_card.js :
var storedMenu = JSON.parse(products);
//Some other stuff using storedMenu
Anyways, since I have multiple json files for different "categories" for my project and a SINGLE javascript file "menu_card.js" that must output some HTML content based on the json content, the problem is that I already have a lot of json files and they all have the same object name and I don't plan on changing it for every single file ( products = ... ). Is it possible to maybe pass the json file name from the href inside the HTML to the javascript function that will use it for the JSON.parse()?
I think I was clear enough with my issue, if something is unclear or not specified, I can easily edit the post. Thank you in advance!
Well you can change the script import like that
<script type="text/javascript" src="first.json">
fetch('/first.json')
.then(response => response.json())
.then( json => {
window.products = (window.products || []);
json.forEach( p => window.products.push(p) );
});
</script>
But files must be pure JSON
[
{
"name": "Hoodies",
"description": "This are some hoodies.",
"price": "90"
}
]
Rewrite them programmaticaly.
You could also rewrite then like below but it will change all the solution.
{
"name": "Hoodies",
"description": "This are some hoodies.",
"price": "90"
}
And so on... so everything will be available in window.products.
As it can be long to rewrite, you can do it for every file with something like
<script type="text/javascript" src="first.json">
Promise.all([ '/first.json', '/second.json']
.map( file => fetch(file).then( r => r.json() ) )
)
.then( allProducts => allProducts.flat() )
.then( allProducts => window.products = allProducts)
;
});
</script>

Searching JSON, but NOT case sensitive [duplicate]

This question already has answers here:
Case-insensitive search
(12 answers)
Closed 2 years ago.
So, the title pretty much says it all. I want to search a JSON, but try and not make it case sensitive. So here is my JSON file:
{ "Data" :
[
{"Name": "Widget", "Price": "25.00", "Quantity": "5" },
{"Name": "Thing", "Price": "15.00", "Quantity": "5" },
{"Name": "Doodad", "Price": "5.00", "Quantity": "10" }
]
}
Unfortunately for me, I have not coded in a long time so basically I wrote the JavaScript part of my code in the HTML file also. It's a bit muddled together:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<form id="form1">
What product do you wish to find? <input name="name" type="text" size="20">
</form>
<button id="fetchUserDataBtn">Cauta</button>
</div>
<hr>
<div id="response"></div>
<script>
document.getElementById('fetchUserDataBtn').addEventListener('click', fetchUserData);
function fetchUserData(){
fetch('Vlad3.json')
.then(response => response.json())
.then(Data => {
let output = "Product list"
output += '<ul>';
var cauta1, cauta2;
cauta1=document.getElementById("form1");
cauta2=cauta1.elements["name"].value;
console.log(cauta2);
var nr=0;
Data.Data.forEach(function(Data) {
if(Data.Name==cauta2)
{nr++;
output += "Product "+Data.Name;
output+="<br>";
output+="Price "+Data.Price;
output+="<br>";
output+="Quantity "+Data.Quantity;
}
});
if(nr==0) {output+="We are sorry, this is not available";}
output += '</ul>'
document.getElementById("response").innerHTML = output;
});
}
</script>
</body>
</html>
Can I manage to add a function somewhere in here, so that when the user introduces "Thing" or "Widget" in the search area, it will find the product, even though it's not written exactly like in the JSON file?
Use .toLowerCase or .toUpperCase to do a case-insensitive compare.
if(Data.Name.toLowerCase()===cauta2.toLowerCase())

Using recursion in a Vue component with JSON

I currently have a set of nested templates that loops through JSON. It outputs the key, checks if the value is not an object, outputs the value if it's not an object, otherwise it goes deeper and traverses the inner object/array for that property. It goes about 3 layers deep currently, but may potentially have to go further.
This makes it a good candidate for recursion. I'm new to front-end languages/frameworks, and I am having trouble finding good resources on finding a good resource for how to traverse JSON dynamically with Vue. This was the best I could, but I'm not using predictable properties like label/node/nodes.
I guess a good place to start would be the Vue.component template. How do I pass in the JSON from the main Vue instance, and then how do I set the template to dynamically traverse the JSON?
HMTL
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Vue: Recursion</title>
<!-- CDNs -->
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.13/dist/vue.js"></script>
<!-- JS -->
<script src="app.js" charset="utf-8"></script>
</head>
<body>
<main id="app">
<template>
<section>
<recursive-component></recursive-component>
</section>
</template>
</main>
</body>
</html>
Javascript
$(function () {
// Get JSON
$.getJSON("./data.json", function (json) {
app.json = json
});
Vue.component('recursive-component', function() {
template: `
<recursive-component
v-if="node !== null"
v-for="(node, key) in nodes"
:nodes="node.nodes"
:key="node.key"
>
</recursive-component>`
});
var app = new Vue({
el: `#app`,
data: {
json: null
}
});
});
Generic JSON
{
"details": {
"manufacturer": "BMW",
"seats": 4,
"engine": {
"torque": 500,
"hp": 600
},
"breaks": {
"front": {
"type": "XYZ",
"capacity": 1234
}
}
}
}
The key of the solution is just checking if the data is a value or an object, I made this example assuming values are only numbers and strings (because to check if variable is an object is quite complicated StackOverflow), then the recursive component just displays the key/value accordingly.
const jsonData = {
"details": {
"manufacturer": "BMW",
"seats": 4,
"engine": {
"torque": 500,
"hp": 600
},
"breaks": {
"front": {
"type": "XYZ",
"capacity": 1234
}
}
}
};
Vue.component("my-recursive-component", {
template: '#my-recursive-component',
props: ["depth", "payload"],
data() {
},
computed: {
indent() {
return { transform: `translate(${this.depth * 10}px)` }
},
type() {
if (typeof this.payload === "string" || typeof this.payload === "number") {
return "value";
}
return "obj";
},
list() {
if (this.type === "obj") {
return Object.keys(this.payload);
}
return undefined;
}
}
});
const app = new Vue({
el: "#app",
data() {
jsonData
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
Recursive Component Demo:
<my-recursive-component
:payload="jsonData"
:depth="0"
>
</my-recursive-component>
</div>
<script type="text/x-template" id="my-recursive-component">
<div>
<div
v-if="type === 'obj'" :style="indent">
<div v-for="item in list">
Key: {{item}}
<my-recursive-component
:payload="payload[item]"
:depth="depth + 1"
>
<my-recursive-component/>
</div>
</div>
<div
v-if="type === 'value'" :style="indent">
Value: {{payload}}
</div>
</div>
</script>

Pass JSON to JQuery function Javascript

We have a very simpel Google Apps Script Web App, which purpose is to show JSON data in a HTML drop-down-list. The JSON file exists in Google Drive. Inspiration code from: http://jsfiddle.net/manoj_admlab/Mta5b/3/
But when we are trying to 'Fetch Json' no data is loaded in to the dropdown-list:
index.html
<!DOCTYPE html>
<html>
<br> <br>
<center>
<head>
<base target="_top">
</head>
<body>
<select id="destinations">
<option value="">Select</option>
</select>
Fetch JSON
</center>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
google.script.run.getJson(); // Runs the function "getJson();" in Code.gs
$('#fetch').click(function(s) {
$.post(s, {json: JSON.stringify(json)}, function(data) {
$.each(data.Destinations, function(i, v) {
$('#destinations').append('<option value="' + v.destinationID + '">' + v.destinationName + '</option>');
});
});
});
</script>
</body>
</html>
Code.gs
function doGet() {
var template = HtmlService.createTemplateFromFile('index');
var htmlOutput = template.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
return htmlOutput;
}
function getJson() {
var files = DriveApp.getFilesByName("jsonData.json");
var file = files.next();
var JSONDATA = file.getAs("application/json").getDataAsString();
//JSONDATA = JSON.stringify(JSONDATA);
JSONDATA = JSON.parse(JSONDATA);
Logger.log(JSONDATA);
click(JSONDATA); // <-- Trying to pass this data to "$('#fetch').click(function(s) {"
}
jsonData.json
{
"options": {
"Destinations": [
{
"destinationName": "London",
"destinationID": "lon"
},
{
"destinationName": "New York",
"destinationID": "nyc"
},
{
"destinationName": "Paris",
"destinationID": "par"
},
{
"destinationName": "Rome",
"destinationID": "rom"
}
]
}
}
You have to return the data in getJson() function, and when calling it, you need to pass a callback, with withSuccessHandler(), as such:
in HTML:
function justLog(e){
console.log(e);
}
$('#fetch').click(function(s) {
google.script.run.withSuccessHandler(justLog).getJson(); // Runs the function "getJson();" in Code.gs
});
in code.gs, finish the function with:
return JSONDATA;
Thanks Kriggs! This worked out great:
Index.html:
<!DOCTYPE html>
<html>
<head>
<select id="dropDownDest">
</select>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
function onSuccess(json) {
$.each(json.Cars, function (key, value) {
$("#dropDownDest").append($('<option></option>').val(value.carID).html(value.CarType));
});
$('#dropDownDest').change(function () {
alert($(this).val());
//Code to select image based on selected car id
});
}
google.script.run.withSuccessHandler(onSuccess)
.jsonData();
</script>
</head>
</html>
Code.gs:
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function jsonData() {
var a = {
Cars: [{
"CarType": "BMW",
"carID": "bmw123"
}, {
"CarType": "mercedes",
"carID": "merc123"
}, {
"CarType": "volvo",
"carID": "vol123r"
}, {
"CarType": "ford",
"carID": "ford123"
}]
};
Logger.log(a);
return a;
}

How to use the http.get method in angular to fetch the json data?

I created a funnel chart in java script . And converted into angular And now I'm trying to use the http.get method in angular to fetch the json data. And I'm stuck here and got confused in this part
And now let me show u my code part
---index.html---
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>FusionCharts - Funnel 3D Chart</title>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<script data-require="angular.js#1.4.0-beta.6" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script>
<script type='text/javascript' src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script type='text/javascript' src="http://static.fusioncharts.com/code/latest/fusioncharts.widgets.js"></script>
<script type='text/javascript' src='/js/lib/dummy.js'></script>
<script type='text/javascript' src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js"></script>
<script src="practice.js"></script>
</head>
<body ng-app="myApp">
<!-- A funnel 3D Chart showing a conversion analysis in percentage of visiting to purchase in Harry's Supermart website last year
Attribute :
# showPercentValues - set to 1 to show the values in percentage.
-->
<div id="chart-container" ng-controller="ParentCtrl" ng-init='load()' ng-model="dataSource1">FusionCharts will render here</div>
</body>
</html>
---script.js---
// Code goes here
//creating an application module
var myApp = angular.module("myApp", []);
//The below code will read the data from student.json file and will pass to the $scope variable
myApp.controller("ParentCtrl", function($scope, $http)
{
$scope.load = function(){
//alert("2");
FusionCharts.ready(function () {
//alert("1");
var conversionChart = new FusionCharts({
type: 'funnel',
renderAt: 'chart-container',
width: "100%",
dataFormat: 'json',
dataSource : "dataSource1"
});
$http.get('chart.json') //reading the studentRecord.json file
.success
(function(data1){
$scope.dataSource1 = data1;// binding the data to the $scope variable
});
conversionChart.render();
});
};
});
----chart.json----
{
"chart": {
"caption": "Ensource sales report",
"subcaption": "Purchase - Conversion analysis for last year",
"decimals": "1",
"isHollow": "0",
"isSliced": "1",
"labelDistance": "15",
"plotTooltext": "Success : $percentOfPrevValue",
"theme": "fint",
"baseFontSize":"18"
},
"data":
[
{
"label": "Total",
"value": "385634"
},
{
"label": "Contacts",
"value": "175631"
},
{
"label": "Leads",
"value": "84564"
},
{
"label": "Sanctioned",
"value": "35654"
},
{
"label": "Disbursed",
"value": "12342"
}
]
}
Plunker:http:http://plnkr.co/edit/HUKvROQv8wIiFfx6uZBk?p=preview
Here i need to fetch the json data for dataSource :but not able to do that
All the script and css for the funnel chart is been included in index.html. My oly work is to fetch the json data using the http.get method.Plz help me with this
And thanks in advance ...
It seems you were just passing the incorrect param to the dataSource field. After some playing around with your plunker, instead of passing it a function where the $http call was executed, I passed it the data itself, as you can see below.
var myApp = angular.module("myApp", []);
//The below code will read the data from student.json file and will pass to the $scope variable
myApp.controller("ParentCtrl", function($scope, $http) {
$http.get('./chart.json') //reading the studentRecord.json file
.success(function(data1) {
$scope.dataSource = data1; // binding the data to the $scope variable
FusionCharts.ready(function() {
//alert("1");
var conversionChart = new FusionCharts({
type: 'funnel',
renderAt: 'chart-container',
width: "100%",
dataFormat: 'json',
dataSource: $scope.dataSource
});
conversionChart.render();
});
});
});
Notice I wrapped the code inside $http's success callback, so that we know that the data is present at the moment of rendering.
You can see the working plunker here.

Categories