1660572300
Search docs, crates, builtin attributes, official books, and error codes, etc in your address bar instantly.
rustup docs --std
):yet
, :book
, :stable
, :label
, :tool
, :mirror
, :update
and :history
etc)Input keyword rs in the address bar, press Space
to activate the search bar. Then enter any word you want to search, the extension will response the related search results instantly.
jsonnet is required before getting started. To install jsonnet
, please check jsonnet
's README. For Linux users, the snap
is a good choice to install jsonnet.
$ git clone --recursive https://github.com/huhu/rust-search-extension
Cloning into 'rust-search-extension'...
$ cd rust-search-extension
$ make chrome # For Chrome version
$ make firefox # For Firefox version
$ make edge # For Edge version
Author: huhu
Source code: https://github.com/huhu/rust-search-extension
License: Apache-2.0, MIT licenses found
#rust #rustlang
1643176207
Serde
*Serde is a framework for serializing and deserializing Rust data structures efficiently and generically.*
You may be looking for:
#[derive(Serialize, Deserialize)]
Click to show Cargo.toml. Run this code in the playground.
[dependencies]
# The core APIs, including the Serialize and Deserialize traits. Always
# required when using Serde. The "derive" feature is only required when
# using #[derive(Serialize, Deserialize)] to make Serde work with structs
# and enums defined in your crate.
serde = { version = "1.0", features = ["derive"] }
# Each data format lives in its own crate; the sample code below uses JSON
# but you may be using a different one.
serde_json = "1.0"
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let point = Point { x: 1, y: 2 };
// Convert the Point to a JSON string.
let serialized = serde_json::to_string(&point).unwrap();
// Prints serialized = {"x":1,"y":2}
println!("serialized = {}", serialized);
// Convert the JSON string back to a Point.
let deserialized: Point = serde_json::from_str(&serialized).unwrap();
// Prints deserialized = Point { x: 1, y: 2 }
println!("deserialized = {:?}", deserialized);
}
Serde is one of the most widely used Rust libraries so any place that Rustaceans congregate will be able to help you out. For chat, consider trying the #rust-questions or #rust-beginners channels of the unofficial community Discord (invite: https://discord.gg/rust-lang-community), the #rust-usage or #beginners channels of the official Rust Project Discord (invite: https://discord.gg/rust-lang), or the #general stream in Zulip. For asynchronous, consider the [rust] tag on StackOverflow, the /r/rust subreddit which has a pinned weekly easy questions post, or the Rust Discourse forum. It's acceptable to file a support issue in this repo but they tend not to get as many eyes as any of the above and may get closed without a response after some time.
Download Details:
Author: serde-rs
Source Code: https://github.com/serde-rs/serde
License: View license
1637936640
Bem-vindo ao tutorial de hoje. No tutorial de hoje, aprenderemos como construir filtros e pesquisar produtos. Para criar este projeto, precisamos de HTML, CSS e Javascript. Como este é um projeto bastante avançado, eu não o recomendaria para um iniciante em javascript. Se você é um intermediário ou especialista em javascript, pode definitivamente ir em frente e fazer este.
Vamos ter uma visão geral do que esse projeto realmente é. O projeto inclui uma série de cartões de produtos. Cada um desses cartões tem um nome, preço e categoria atribuídos a eles. Acima dessas tags, há uma barra de pesquisa onde os usuários podem pesquisar um produto com base em seu nome.
Abaixo da barra de pesquisa, existe um grupo de botões. Cada um desses botões possui um nome de categoria. Quando o usuário clica em qualquer um desses botões, os produtos correspondentes a essa categoria específica serão exibidos.
Agora vamos primeiro criar a estrutura do diretório do projeto para que possamos começar a codificar. Começamos criando uma pasta de projeto chamada - 'Filtros e Pesquisa de Produto'. Dentro desta pasta, criamos três arquivos. O primeiro é index.html
, o segundo é style.css
e o terceiro é script.js
. Esses arquivos são documentos HTML, folhas de estilo e arquivos de script, respectivamente.
Começamos com o código HTML. Primeiro, copie o código abaixo e cole em seu arquivo HTML.
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Product Filter And Search</title>
<!-- Google Font -->
<link
href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500&display=swap"
rel="stylesheet"
/>
<!-- Stylesheet -->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="wrapper">
<div id="search-container">
<input
type="search"
id="search-input"
placeholder="Search product name here.."
/>
<button id="search">Search</button>
</div>
<div id="buttons">
<button class="button-value" onclick="filterProduct('all')">All</button>
<button class="button-value" onclick="filterProduct('Topwear')">
Topwear
</button>
<button class="button-value" onclick="filterProduct('Bottomwear')">
Bottomwear
</button>
<button class="button-value" onclick="filterProduct('Jacket')">
Jacket
</button>
<button class="button-value" onclick="filterProduct('Watch')">
Watch
</button>
</div>
<div id="products"></div>
</div>
<!-- Script -->
<script src="script.js"></script>
</body>
</html>
Em seguida, para adicionar estilos a este projeto, usamos CSS. Agora copie o código abaixo e cole-o em seu arquivo CSS.
* {
padding: 0;
margin: 0;
box-sizing: border-box;
border: none;
outline: none;
font-family: "Poppins", sans-serif;
}
body {
background-color: #f5f8ff;
}
.wrapper {
width: 95%;
margin: 0 auto;
}
#search-container {
margin: 1em 0;
}
#search-container input {
background-color: transparent;
width: 40%;
border-bottom: 2px solid #110f29;
padding: 1em 0.3em;
}
#search-container input:focus {
border-bottom-color: #6759ff;
}
#search-container button {
padding: 1em 2em;
margin-left: 1em;
background-color: #6759ff;
color: #ffffff;
border-radius: 5px;
margin-top: 0.5em;
}
.button-value {
border: 2px solid #6759ff;
padding: 1em 2.2em;
border-radius: 3em;
background-color: transparent;
color: #6759ff;
cursor: pointer;
}
.active {
background-color: #6759ff;
color: #ffffff;
}
#products {
display: grid;
grid-template-columns: auto auto auto;
grid-column-gap: 1.5em;
padding: 2em 0;
}
.card {
background-color: #ffffff;
max-width: 18em;
margin-top: 1em;
padding: 1em;
border-radius: 5px;
box-shadow: 1em 2em 2.5em rgba(1, 2, 68, 0.08);
}
.image-container {
text-align: center;
}
img {
max-width: 100%;
object-fit: contain;
height: 15em;
}
.container {
padding-top: 1em;
color: #110f29;
}
.container h5 {
font-weight: 500;
}
.hide {
display: none;
}
@media screen and (max-width: 720px) {
img {
max-width: 100%;
object-fit: contain;
height: 10em;
}
.card {
max-width: 10em;
margin-top: 1em;
}
#products {
grid-template-columns: auto auto;
grid-column-gap: 1em;
}
}
Finalmente, precisamos adicionar funcionalidade ao filtro e também implementar a função de pesquisa. Para fazer funcionar, adicionamos javascript. Copie o código abaixo e cole em seu arquivo javascript.
let products = {
data: [
{
productName: "Regular White T-Shirt",
category: "Topwear",
price: "30",
image: "white-tshirt.jpg",
},
{
productName: "Beige Short Skirt",
category: "Bottomwear",
price: "49",
image: "short-skirt.jpg",
},
{
productName: "Sporty SmartWatch",
category: "Watch",
price: "99",
image: "sporty-smartwatch.jpg",
},
{
productName: "Basic Knitted Top",
category: "Topwear",
price: "29",
image: "knitted-top.jpg",
},
{
productName: "Black Leather Jacket",
category: "Jacket",
price: "129",
image: "black-leather-jacket.jpg",
},
{
productName: "Stylish Pink Trousers",
category: "Bottomwear",
price: "89",
image: "pink-trousers.jpg",
},
{
productName: "Brown Men's Jacket",
category: "Jacket",
price: "189",
image: "brown-jacket.jpg",
},
{
productName: "Comfy Gray Pants",
category: "Bottomwear",
price: "49",
image: "comfy-gray-pants.jpg",
},
],
};
for (let i of products.data) {
//Create Card
let card = document.createElement("div");
//Card should have category and should stay hidden initially
card.classList.add("card", i.category, "hide");
//image div
let imgContainer = document.createElement("div");
imgContainer.classList.add("image-container");
//img tag
let image = document.createElement("img");
image.setAttribute("src", i.image);
imgContainer.appendChild(image);
card.appendChild(imgContainer);
//container
let container = document.createElement("div");
container.classList.add("container");
//product name
let name = document.createElement("h5");
name.classList.add("product-name");
name.innerText = i.productName.toUpperCase();
container.appendChild(name);
//price
let price = document.createElement("h6");
price.innerText = "$" + i.price;
container.appendChild(price);
card.appendChild(container);
document.getElementById("products").appendChild(card);
}
//parameter passed from button (Parameter same as category)
function filterProduct(value) {
//Button class code
let buttons = document.querySelectorAll(".button-value");
buttons.forEach((button) => {
//check if value equals innerText
if (value.toUpperCase() == button.innerText.toUpperCase()) {
button.classList.add("active");
} else {
button.classList.remove("active");
}
});
//select all cards
let elements = document.querySelectorAll(".card");
//loop through all cards
elements.forEach((element) => {
//display all cards on 'all' button click
if (value == "all") {
element.classList.remove("hide");
} else {
//Check if element contains category class
if (element.classList.contains(value)) {
//display element based on category
element.classList.remove("hide");
} else {
//hide other elements
element.classList.add("hide");
}
}
});
}
//Search button click
document.getElementById("search").addEventListener("click", () => {
//initializations
let searchInput = document.getElementById("search-input").value;
let elements = document.querySelectorAll(".product-name");
let cards = document.querySelectorAll(".card");
//loop through all elements
elements.forEach((element, index) => {
//check if text includes the search value
if (element.innerText.includes(searchInput.toUpperCase())) {
//display matching card
cards[index].classList.remove("hide");
} else {
//hide others
cards[index].classList.add("hide");
}
});
});
//Initially display all products
window.onload = () => {
filterProduct("all");
};
Sua pesquisa e filtro de produto agora estão prontos. Espero que tenha gostado do tutorial.
1637912634
Bienvenido al tutorial de hoy. En el tutorial de hoy, aprenderemos cómo crear filtros y buscar productos. Para crear este proyecto, necesitamos HTML, CSS y Javascript. Dado que este es un proyecto bastante avanzado, no se lo recomendaría a un principiante de JavaScript. Si eres un intermedio o un experto en javascript, definitivamente puedes seguir adelante y hacer este.
Tengamos una visión general de lo que realmente es este proyecto. El proyecto incluye una serie de fichas de producto. Cada una de estas tarjetas tiene asignado un nombre, precio y categoría. Por encima de estas etiquetas, hay una barra de búsqueda donde los usuarios pueden buscar un producto según su nombre.
Debajo de la barra de búsqueda, hay un grupo de botones. Cada uno de estos botones tiene un nombre de categoría. Cuando el usuario haga clic en cualquiera de estos botones, se mostrarán los productos correspondientes a esa categoría en particular.
Ahora, primero creemos la estructura del directorio del proyecto para que podamos comenzar a codificar. Comenzamos creando una carpeta de proyecto llamada - 'Filtros y búsqueda de productos'. Dentro de esta carpeta creamos tres archivos. El primero es index.html
, el segundo es style.css
y el tercero es script.js
. Estos archivos son documentos HTML, hojas de estilo y archivos de script, respectivamente.
Empezamos con el código HTML. Primero, copie el código a continuación y péguelo en su archivo HTML.
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Product Filter And Search</title>
<!-- Google Font -->
<link
href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500&display=swap"
rel="stylesheet"
/>
<!-- Stylesheet -->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="wrapper">
<div id="search-container">
<input
type="search"
id="search-input"
placeholder="Search product name here.."
/>
<button id="search">Search</button>
</div>
<div id="buttons">
<button class="button-value" onclick="filterProduct('all')">All</button>
<button class="button-value" onclick="filterProduct('Topwear')">
Topwear
</button>
<button class="button-value" onclick="filterProduct('Bottomwear')">
Bottomwear
</button>
<button class="button-value" onclick="filterProduct('Jacket')">
Jacket
</button>
<button class="button-value" onclick="filterProduct('Watch')">
Watch
</button>
</div>
<div id="products"></div>
</div>
<!-- Script -->
<script src="script.js"></script>
</body>
</html>
A continuación, para agregar estilos a este proyecto, usamos CSS. Ahora copie el código a continuación y péguelo en su archivo CSS.
* {
padding: 0;
margin: 0;
box-sizing: border-box;
border: none;
outline: none;
font-family: "Poppins", sans-serif;
}
body {
background-color: #f5f8ff;
}
.wrapper {
width: 95%;
margin: 0 auto;
}
#search-container {
margin: 1em 0;
}
#search-container input {
background-color: transparent;
width: 40%;
border-bottom: 2px solid #110f29;
padding: 1em 0.3em;
}
#search-container input:focus {
border-bottom-color: #6759ff;
}
#search-container button {
padding: 1em 2em;
margin-left: 1em;
background-color: #6759ff;
color: #ffffff;
border-radius: 5px;
margin-top: 0.5em;
}
.button-value {
border: 2px solid #6759ff;
padding: 1em 2.2em;
border-radius: 3em;
background-color: transparent;
color: #6759ff;
cursor: pointer;
}
.active {
background-color: #6759ff;
color: #ffffff;
}
#products {
display: grid;
grid-template-columns: auto auto auto;
grid-column-gap: 1.5em;
padding: 2em 0;
}
.card {
background-color: #ffffff;
max-width: 18em;
margin-top: 1em;
padding: 1em;
border-radius: 5px;
box-shadow: 1em 2em 2.5em rgba(1, 2, 68, 0.08);
}
.image-container {
text-align: center;
}
img {
max-width: 100%;
object-fit: contain;
height: 15em;
}
.container {
padding-top: 1em;
color: #110f29;
}
.container h5 {
font-weight: 500;
}
.hide {
display: none;
}
@media screen and (max-width: 720px) {
img {
max-width: 100%;
object-fit: contain;
height: 10em;
}
.card {
max-width: 10em;
margin-top: 1em;
}
#products {
grid-template-columns: auto auto;
grid-column-gap: 1em;
}
}
Finalmente, necesitamos agregar funcionalidad al filtro y también implementar la función de búsqueda. Para que funcione, agregamos javascript. Copie el código que se proporciona a continuación y péguelo en su archivo javascript.
let products = {
data: [
{
productName: "Regular White T-Shirt",
category: "Topwear",
price: "30",
image: "white-tshirt.jpg",
},
{
productName: "Beige Short Skirt",
category: "Bottomwear",
price: "49",
image: "short-skirt.jpg",
},
{
productName: "Sporty SmartWatch",
category: "Watch",
price: "99",
image: "sporty-smartwatch.jpg",
},
{
productName: "Basic Knitted Top",
category: "Topwear",
price: "29",
image: "knitted-top.jpg",
},
{
productName: "Black Leather Jacket",
category: "Jacket",
price: "129",
image: "black-leather-jacket.jpg",
},
{
productName: "Stylish Pink Trousers",
category: "Bottomwear",
price: "89",
image: "pink-trousers.jpg",
},
{
productName: "Brown Men's Jacket",
category: "Jacket",
price: "189",
image: "brown-jacket.jpg",
},
{
productName: "Comfy Gray Pants",
category: "Bottomwear",
price: "49",
image: "comfy-gray-pants.jpg",
},
],
};
for (let i of products.data) {
//Create Card
let card = document.createElement("div");
//Card should have category and should stay hidden initially
card.classList.add("card", i.category, "hide");
//image div
let imgContainer = document.createElement("div");
imgContainer.classList.add("image-container");
//img tag
let image = document.createElement("img");
image.setAttribute("src", i.image);
imgContainer.appendChild(image);
card.appendChild(imgContainer);
//container
let container = document.createElement("div");
container.classList.add("container");
//product name
let name = document.createElement("h5");
name.classList.add("product-name");
name.innerText = i.productName.toUpperCase();
container.appendChild(name);
//price
let price = document.createElement("h6");
price.innerText = "$" + i.price;
container.appendChild(price);
card.appendChild(container);
document.getElementById("products").appendChild(card);
}
//parameter passed from button (Parameter same as category)
function filterProduct(value) {
//Button class code
let buttons = document.querySelectorAll(".button-value");
buttons.forEach((button) => {
//check if value equals innerText
if (value.toUpperCase() == button.innerText.toUpperCase()) {
button.classList.add("active");
} else {
button.classList.remove("active");
}
});
//select all cards
let elements = document.querySelectorAll(".card");
//loop through all cards
elements.forEach((element) => {
//display all cards on 'all' button click
if (value == "all") {
element.classList.remove("hide");
} else {
//Check if element contains category class
if (element.classList.contains(value)) {
//display element based on category
element.classList.remove("hide");
} else {
//hide other elements
element.classList.add("hide");
}
}
});
}
//Search button click
document.getElementById("search").addEventListener("click", () => {
//initializations
let searchInput = document.getElementById("search-input").value;
let elements = document.querySelectorAll(".product-name");
let cards = document.querySelectorAll(".card");
//loop through all elements
elements.forEach((element, index) => {
//check if text includes the search value
if (element.innerText.includes(searchInput.toUpperCase())) {
//display matching card
cards[index].classList.remove("hide");
} else {
//hide others
cards[index].classList.add("hide");
}
});
});
//Initially display all products
window.onload = () => {
filterProduct("all");
};
Su búsqueda y filtro de productos ya están listos. Espero que hayan disfrutado el tutorial.
1637931784
Bienvenue dans le tutoriel d'aujourd'hui. Dans le didacticiel d'aujourd'hui, nous allons apprendre à créer des filtres et à rechercher des produits. Pour créer ce projet, nous avons besoin de HTML, CSS et Javascript. Comme il s'agit d'un projet assez avancé, je ne le recommanderais pas à un débutant en javascript. Si vous êtes un intermédiaire ou un expert en javascript, vous pouvez certainement aller de l'avant et créer celui-ci.
Ayons un aperçu de ce qu'est réellement ce projet. Le projet comprend une série de fiches produits. Chacune de ces cartes a un nom, un prix et une catégorie qui leur sont attribués. Au-dessus de ces balises, il y a une barre de recherche où les utilisateurs peuvent rechercher un produit en fonction de son nom.
Sous la barre de recherche, il y a un groupe de boutons. Chacun de ces boutons a un nom de catégorie. Lorsque l'utilisateur clique sur l'un de ces boutons, les produits correspondant à cette catégorie particulière seront affichés.
Maintenant, créons d'abord la structure du répertoire du projet afin que nous puissions commencer à coder. Nous commençons par créer un dossier de projet nommé - « Filtres et recherche de produits ». Dans ce dossier, nous créons trois fichiers. Le premier est index.html
, le second est style.css
et le troisième est script.js
. Ces fichiers sont respectivement des documents HTML, des feuilles de style et des fichiers de script.
Nous commençons par le code HTML. Tout d'abord, copiez le code ci-dessous et collez-le dans votre fichier HTML.
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Product Filter And Search</title>
<!-- Google Font -->
<link
href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500&display=swap"
rel="stylesheet"
/>
<!-- Stylesheet -->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="wrapper">
<div id="search-container">
<input
type="search"
id="search-input"
placeholder="Search product name here.."
/>
<button id="search">Search</button>
</div>
<div id="buttons">
<button class="button-value" onclick="filterProduct('all')">All</button>
<button class="button-value" onclick="filterProduct('Topwear')">
Topwear
</button>
<button class="button-value" onclick="filterProduct('Bottomwear')">
Bottomwear
</button>
<button class="button-value" onclick="filterProduct('Jacket')">
Jacket
</button>
<button class="button-value" onclick="filterProduct('Watch')">
Watch
</button>
</div>
<div id="products"></div>
</div>
<!-- Script -->
<script src="script.js"></script>
</body>
</html>
Ensuite, pour ajouter des styles à ce projet, nous utilisons CSS. Copiez maintenant le code ci-dessous et collez-le dans votre fichier CSS.
* {
padding: 0;
margin: 0;
box-sizing: border-box;
border: none;
outline: none;
font-family: "Poppins", sans-serif;
}
body {
background-color: #f5f8ff;
}
.wrapper {
width: 95%;
margin: 0 auto;
}
#search-container {
margin: 1em 0;
}
#search-container input {
background-color: transparent;
width: 40%;
border-bottom: 2px solid #110f29;
padding: 1em 0.3em;
}
#search-container input:focus {
border-bottom-color: #6759ff;
}
#search-container button {
padding: 1em 2em;
margin-left: 1em;
background-color: #6759ff;
color: #ffffff;
border-radius: 5px;
margin-top: 0.5em;
}
.button-value {
border: 2px solid #6759ff;
padding: 1em 2.2em;
border-radius: 3em;
background-color: transparent;
color: #6759ff;
cursor: pointer;
}
.active {
background-color: #6759ff;
color: #ffffff;
}
#products {
display: grid;
grid-template-columns: auto auto auto;
grid-column-gap: 1.5em;
padding: 2em 0;
}
.card {
background-color: #ffffff;
max-width: 18em;
margin-top: 1em;
padding: 1em;
border-radius: 5px;
box-shadow: 1em 2em 2.5em rgba(1, 2, 68, 0.08);
}
.image-container {
text-align: center;
}
img {
max-width: 100%;
object-fit: contain;
height: 15em;
}
.container {
padding-top: 1em;
color: #110f29;
}
.container h5 {
font-weight: 500;
}
.hide {
display: none;
}
@media screen and (max-width: 720px) {
img {
max-width: 100%;
object-fit: contain;
height: 10em;
}
.card {
max-width: 10em;
margin-top: 1em;
}
#products {
grid-template-columns: auto auto;
grid-column-gap: 1em;
}
}
Enfin, nous devons ajouter des fonctionnalités au filtre et également implémenter la fonction de recherche. Pour que cela fonctionne, nous ajoutons javascript. Copiez le code ci-dessous et collez-le dans votre fichier javascript.
let products = {
data: [
{
productName: "Regular White T-Shirt",
category: "Topwear",
price: "30",
image: "white-tshirt.jpg",
},
{
productName: "Beige Short Skirt",
category: "Bottomwear",
price: "49",
image: "short-skirt.jpg",
},
{
productName: "Sporty SmartWatch",
category: "Watch",
price: "99",
image: "sporty-smartwatch.jpg",
},
{
productName: "Basic Knitted Top",
category: "Topwear",
price: "29",
image: "knitted-top.jpg",
},
{
productName: "Black Leather Jacket",
category: "Jacket",
price: "129",
image: "black-leather-jacket.jpg",
},
{
productName: "Stylish Pink Trousers",
category: "Bottomwear",
price: "89",
image: "pink-trousers.jpg",
},
{
productName: "Brown Men's Jacket",
category: "Jacket",
price: "189",
image: "brown-jacket.jpg",
},
{
productName: "Comfy Gray Pants",
category: "Bottomwear",
price: "49",
image: "comfy-gray-pants.jpg",
},
],
};
for (let i of products.data) {
//Create Card
let card = document.createElement("div");
//Card should have category and should stay hidden initially
card.classList.add("card", i.category, "hide");
//image div
let imgContainer = document.createElement("div");
imgContainer.classList.add("image-container");
//img tag
let image = document.createElement("img");
image.setAttribute("src", i.image);
imgContainer.appendChild(image);
card.appendChild(imgContainer);
//container
let container = document.createElement("div");
container.classList.add("container");
//product name
let name = document.createElement("h5");
name.classList.add("product-name");
name.innerText = i.productName.toUpperCase();
container.appendChild(name);
//price
let price = document.createElement("h6");
price.innerText = "$" + i.price;
container.appendChild(price);
card.appendChild(container);
document.getElementById("products").appendChild(card);
}
//parameter passed from button (Parameter same as category)
function filterProduct(value) {
//Button class code
let buttons = document.querySelectorAll(".button-value");
buttons.forEach((button) => {
//check if value equals innerText
if (value.toUpperCase() == button.innerText.toUpperCase()) {
button.classList.add("active");
} else {
button.classList.remove("active");
}
});
//select all cards
let elements = document.querySelectorAll(".card");
//loop through all cards
elements.forEach((element) => {
//display all cards on 'all' button click
if (value == "all") {
element.classList.remove("hide");
} else {
//Check if element contains category class
if (element.classList.contains(value)) {
//display element based on category
element.classList.remove("hide");
} else {
//hide other elements
element.classList.add("hide");
}
}
});
}
//Search button click
document.getElementById("search").addEventListener("click", () => {
//initializations
let searchInput = document.getElementById("search-input").value;
let elements = document.querySelectorAll(".product-name");
let cards = document.querySelectorAll(".card");
//loop through all elements
elements.forEach((element, index) => {
//check if text includes the search value
if (element.innerText.includes(searchInput.toUpperCase())) {
//display matching card
cards[index].classList.remove("hide");
} else {
//hide others
cards[index].classList.add("hide");
}
});
});
//Initially display all products
window.onload = () => {
filterProduct("all");
};
Votre recherche de produits et votre filtre sont maintenant prêts. J'espère que vous avez apprécié le tutoriel.
1654894080
Serde JSON
Serde is a framework for serializing and deserializing Rust data structures efficiently and generically.
[dependencies]
serde_json = "1.0"
You may be looking for:
#[derive(Serialize, Deserialize)]
JSON is a ubiquitous open-standard format that uses human-readable text to transmit data objects consisting of key-value pairs.
{
"name": "John Doe",
"age": 43,
"address": {
"street": "10 Downing Street",
"city": "London"
},
"phones": [
"+44 1234567",
"+44 2345678"
]
}
There are three common ways that you might find yourself needing to work with JSON data in Rust.
Serde JSON provides efficient, flexible, safe ways of converting data between each of these representations.
Any valid JSON data can be manipulated in the following recursive enum representation. This data structure is serde_json::Value
.
enum Value {
Null,
Bool(bool),
Number(Number),
String(String),
Array(Vec<Value>),
Object(Map<String, Value>),
}
A string of JSON data can be parsed into a serde_json::Value
by the serde_json::from_str
function. There is also from_slice
for parsing from a byte slice &[u8] and from_reader
for parsing from any io::Read
like a File or a TCP stream.
use serde_json::{Result, Value};
fn untyped_example() -> Result<()> {
// Some JSON input data as a &str. Maybe this comes from the user.
let data = r#"
{
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
}"#;
// Parse the string of data into serde_json::Value.
let v: Value = serde_json::from_str(data)?;
// Access parts of the data by indexing with square brackets.
println!("Please call {} at the number {}", v["name"], v["phones"][0]);
Ok(())
}
The result of square bracket indexing like v["name"]
is a borrow of the data at that index, so the type is &Value
. A JSON map can be indexed with string keys, while a JSON array can be indexed with integer keys. If the type of the data is not right for the type with which it is being indexed, or if a map does not contain the key being indexed, or if the index into a vector is out of bounds, the returned element is Value::Null
.
When a Value
is printed, it is printed as a JSON string. So in the code above, the output looks like Please call "John Doe" at the number "+44 1234567"
. The quotation marks appear because v["name"]
is a &Value
containing a JSON string and its JSON representation is "John Doe"
. Printing as a plain string without quotation marks involves converting from a JSON string to a Rust string with as_str()
or avoiding the use of Value
as described in the following section.
The Value
representation is sufficient for very basic tasks but can be tedious to work with for anything more significant. Error handling is verbose to implement correctly, for example imagine trying to detect the presence of unrecognized fields in the input data. The compiler is powerless to help you when you make a mistake, for example imagine typoing v["name"]
as v["nmae"]
in one of the dozens of places it is used in your code.
Serde provides a powerful way of mapping JSON data into Rust data structures largely automatically.
use serde::{Deserialize, Serialize};
use serde_json::Result;
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
age: u8,
phones: Vec<String>,
}
fn typed_example() -> Result<()> {
// Some JSON input data as a &str. Maybe this comes from the user.
let data = r#"
{
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
}"#;
// Parse the string of data into a Person object. This is exactly the
// same function as the one that produced serde_json::Value above, but
// now we are asking it for a Person as output.
let p: Person = serde_json::from_str(data)?;
// Do things just like with any other Rust data structure.
println!("Please call {} at the number {}", p.name, p.phones[0]);
Ok(())
}
This is the same serde_json::from_str
function as before, but this time we assign the return value to a variable of type Person
so Serde will automatically interpret the input data as a Person
and produce informative error messages if the layout does not conform to what a Person
is expected to look like.
Any type that implements Serde's Deserialize
trait can be deserialized this way. This includes built-in Rust standard library types like Vec<T>
and HashMap<K, V>
, as well as any structs or enums annotated with #[derive(Deserialize)]
.
Once we have p
of type Person
, our IDE and the Rust compiler can help us use it correctly like they do for any other Rust code. The IDE can autocomplete field names to prevent typos, which was impossible in the serde_json::Value
representation. And the Rust compiler can check that when we write p.phones[0]
, then p.phones
is guaranteed to be a Vec<String>
so indexing into it makes sense and produces a String
.
The necessary setup for using Serde's derive macros is explained on the Using derive page of the Serde site.
Serde JSON provides a json!
macro to build serde_json::Value
objects with very natural JSON syntax.
use serde_json::json;
fn main() {
// The type of `john` is `serde_json::Value`
let john = json!({
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
});
println!("first phone number: {}", john["phones"][0]);
// Convert to a string of JSON and print it out
println!("{}", john.to_string());
}
The Value::to_string()
function converts a serde_json::Value
into a String
of JSON text.
One neat thing about the json!
macro is that variables and expressions can be interpolated directly into the JSON value as you are building it. Serde will check at compile time that the value you are interpolating is able to be represented as JSON.
let full_name = "John Doe";
let age_last_year = 42;
// The type of `john` is `serde_json::Value`
let john = json!({
"name": full_name,
"age": age_last_year + 1,
"phones": [
format!("+44 {}", random_phone())
]
});
This is amazingly convenient, but we have the problem we had before with Value
: the IDE and Rust compiler cannot help us if we get it wrong. Serde JSON provides a better way of serializing strongly-typed data structures into JSON text.
A data structure can be converted to a JSON string by serde_json::to_string
. There is also serde_json::to_vec
which serializes to a Vec<u8>
and serde_json::to_writer
which serializes to any io::Write
such as a File or a TCP stream.
use serde::{Deserialize, Serialize};
use serde_json::Result;
#[derive(Serialize, Deserialize)]
struct Address {
street: String,
city: String,
}
fn print_an_address() -> Result<()> {
// Some data structure.
let address = Address {
street: "10 Downing Street".to_owned(),
city: "London".to_owned(),
};
// Serialize it to a JSON string.
let j = serde_json::to_string(&address)?;
// Print, write to a file, or send to an HTTP server.
println!("{}", j);
Ok(())
}
Any type that implements Serde's Serialize
trait can be serialized this way. This includes built-in Rust standard library types like Vec<T>
and HashMap<K, V>
, as well as any structs or enums annotated with #[derive(Serialize)]
.
It is fast. You should expect in the ballpark of 500 to 1000 megabytes per second deserialization and 600 to 900 megabytes per second serialization, depending on the characteristics of your data. This is competitive with the fastest C and C++ JSON libraries or even 30% faster for many use cases. Benchmarks live in the serde-rs/json-benchmark repo.
Serde is one of the most widely used Rust libraries, so any place that Rustaceans congregate will be able to help you out. For chat, consider trying the #rust-questions or #rust-beginners channels of the unofficial community Discord (invite: https://discord.gg/rust-lang-community), the #rust-usage or #beginners channels of the official Rust Project Discord (invite: https://discord.gg/rust-lang), or the #general stream in Zulip. For asynchronous, consider the [rust] tag on StackOverflow, the /r/rust subreddit which has a pinned weekly easy questions post, or the Rust Discourse forum. It's acceptable to file a support issue in this repo, but they tend not to get as many eyes as any of the above and may get closed without a response after some time.
As long as there is a memory allocator, it is possible to use serde_json without the rest of the Rust standard library. This is supported on Rust 1.36+. Disable the default "std" feature and enable the "alloc" feature:
[dependencies]
serde_json = { version = "1.0", default-features = false, features = ["alloc"] }
For JSON support in Serde without a memory allocator, please see the serde-json-core
crate.