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())
Related
This endpoint http://vk-data:8003/v1/entity/ returns this:
[
{
"id": "country",
"url": "http://vk-data:8003/v1/entity/country",
"name": "Countries",
"description": "All the countries in the world"
},
{
"id": "data-site",
"url": "http://vl-data:8003/v1/entity/data-site",
"name": "World data storage",
"description": "A catalog of health data"
}
]
I want to write a function that allows user to access either data-site or country data through a search bar input.
How can I get my code to do that? Here's what I have so far.
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<button id="catalog" onclick="RetrieveCatalog()">Get Catalog</button>
<input type="text" placeholder="Search for User" onChange={(e) => RetrieveEntities(e.target.value)} className="input_search" />
<button onClick={fetchData} className="search_button">Search Github</button>
<script>
//fetch catalog function
function RetrieveCatalog(){
//http request
fetch("http://vk-data:8003/v1/entity/")
.then(function(data){
console.log(data)
return data.json()
})
.then(function(data){})
.catch(error => console.error(error))
}
//fetch catalog function
function RetrieveEntities(){
//http request
fetch("http://vk-data:8003/v1/entity/${entities}")
.then(function(data){
console.log(data)
return data.json()
})
.then(function(data){})
.catch(error => console.error(error))
}
</script>
</body>
</html>
I believe the issue is that you have got confused between JSX and HTML syntax.
There are a few areas where you have gotten mixed up between the two. Here are the places to fix.
In the <input> tag, change the onChange attribute to onchange. Also, surround the function with quotes ("") instead of curly braces ({}).
<input onchange="(e) => RetrieveEntities(e.target.value)" />
In the same <input> tag, change the className attribute to class.
<input class="input_search" />
In the <button> element, change the onClick attribute to onclick, as well as surrounding the value with quotes.
<button onclick="fetch"></button>
In the <button> tag, change className to class.
<button class="search_button"></button>
These changes in your HTML code should help solve the issue.
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>
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);
}
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>
I am making a simple search code. I can't find error. The error message says Uncaught SyntaxError: Unexpected identifier on javascript line 40 (target=document.getElementById("outputPlace").
Do not look at the button, I have not added event listener to it yet.
I just want that when I press enter products are displayed.
HTML CODE
<html>
<head>
<title>Price List </title>
</head>
<body>
<h1> PRICELIST </h1>
<form id="formSearch">
<div>
<label for="searchBox"> Search products here: </label>
<input type="text" placeholder="Type text here to search product" id="searchBox">
</div>
<div id="buttons">
<button id="getAll"> GET ALL PRODUCTS</button>
</div>
</form>
<div id="outputPlace">
</div>
<script src="product.js"></script>
</body>
</html>
JAVASCRIPT CODE
(function(){ //start anonymous function
var list= {
"listOfProducts": [
{
"name":"hard disk",
"price": "50$",
"quality":"good",
},
{
"name":"monitor",
"price":"100$",
"quality": "very good",
},
{
"name":"speakers",
"price":"20$",
"quality": "not bad",
},
{
"name":"headphones",
"price":"12$",
"quality":"bad",
},
{
"name": "mobile phone",
"price": "300$",
"quality": "excellent",
},
{
"name": "usb memory",
"price": "30$",
"quality": "the best",
}
]
},
var target=document.getElementById("outputPlace"),
searchForm=document.getElementById("formSearch"),
productList=list.listOfProducts,
listLength=productList.length,
searchValue=document.getElementById("searchBox"),
searchInput=searchValue.value;
var listMethods = {
searchList: function(event) {
event.preventDefault();
var i;
target.innerHTML="";
if(listLength>0 && searchInput!=="") {
for(i=0;i<listLength;i++) {
var product=productList[i],
whatIsFound=product.name.indexOf(searchInput);
if(whatIsFound!==-1){
target.innerHTML+='<p>'+product.name+', '+product.price+', '+product.quality+'click here to buy</p>'
}
}
}
},
};
searchForm.addEventListener("submit",listMethods.searchList,false);
}) (); //end anonymous function
You have a comma after that large JSON object you defined at the top of your JavaScript, followed by another var.
var list= {
"listOfProducts": [
{
"name":"hard disk",
"price": "50$",
"quality":"good",
},
...[a bunch of stuff]...
},
var target=document.getElementById("outputPlace"),
searchForm=document.getElementById("formSearch"),
productList=list.listOfProducts,
listLength=productList.length,
searchValue=document.getElementById("searchBox"),
searchInput=searchValue.value;
Both of the two other proposed answers would fix this (well ok Otome deleted their answer which was to drop the second var).
Change this
var list = {
...
},
var target=document.getElementById("outputPlace"),
to this:
var list = {
...
};
var target=document.getElementById("outputPlace"),
And you have one more comma at the end of script, after }