I have to read a json file, I followed the following code: stackoverflow
Trying the example shown in the comment, but it's not working for me.
I have to read this file that I have locally, but I'm not succeeding.
Can you give me a hand?
Link: Codesandbox
Code:
fetch("/user.json")
.then(res => res.json())
.then(res => res.results)
.then(res => {
console.log(res);
let u = res.map((suggestion, i) => ({
label: suggestion.email,
name: suggestion.name.first,
surname: suggestion.name.last,
address: suggestion.location.street.name,
email: suggestion.email,
picture: suggestion.picture.thumbnail
}));
let options =
inputLength === 0
? []
: u.filter(suggestion => {
const keep =
count < 5 &&
suggestion.label &&
suggestion.label.slice(0, inputLength).toLowerCase() ===
inputValue;
if (keep) count += 1;
return keep;
});
this.setState({ options });
})
.catch(e => console.log("Er:", e));
You can just use import or require as follows:
const data = require("./myFile.json")
import data from "./myFile.json"
Related
Can someone please assist in following:
I have to assert array with x elements (usually not more than 6 or 7) and if there is any duplicates, it has to throw error - or step to fail. So far I did the following:
Cypress.Commands.add('addTextElementIntoArray', (list) => {
var textsArray = []
cy.xpath(list).each(($el) => {
const text = $el.text().replace(' ', '')
textsArray.push(text)
cy.log(text)
})
})
Tried this solution: Find duplicates, but it does not work in Cypress. How can I solve this?
Thank you in advance
Found solution, and here it is:
Cypress.Commands.add('addTextElementIntoArray', (list) => {
var textsArray = []
var non_unique = []
cy.xpath(list)
.each(($el) => {
const text = $el.text().replace(' ', '')
textsArray.push(text)
cy.log(text)
non_unique = textsArray.filter((item, i) =>
textsArray.includes(item, i + 1)
)
})
.then(() => {
expect(non_unique.length).equal(0)
})
})
Using the answer from the linked question in Cypress,
Cypress.Commands.add('listHasNoDuplicates', (list) => {
cy.xpath(list)
.then($els => [...$els].map(el => el.innerText.trim()))
.then(texts => {
const unique = new Set(texts)
expect(texts.length).to.eq(unique.size)
})
})
})
I am working on my first Vue-Projeect with firebase.
I would like to create locations with particular images and other data.
I am working with a tutorial which is unfortunately a bit outdated. Currently I am struggeling with the connection of firebase storage with firebase database.
I am not able to push the downloadable imageUrl in the firebase storage and store it in the database.
Can you guys help me out here?
Thank you
createLocation( {commit, getters}, payload) {
const location = {
title: payload.title,
location: payload.location,
description: payload.description,
creationDate: payload.creationDate,
rating: payload.rating,
coordinates: payload.coordinates,
filters: payload.filters,
creatorId: getters.user.id
}
let imageUrl
let key
firebase.database().ref('locations').push(location)
.then((data) => {
key = data.key
return key
})
.then(key => {
const filename = payload.image.name
const ext = filename.slice(filename.lastIndexOf('.'))
console.log(payload.image)
return firebase.storage().ref('locations/' + key + ext).put(payload.image)
})
.then(fileData => {
imageUrl = fileData.metadata.getDownloadURL
return firebase.database().ref('meetups').child(key).update({imageUrl: imageUrl})
})
.then(() => {
commit('createLocation', {
...location,
imageUrl:imageUrl,
id: key
})
})
.catch((error) => {
console.log(error)
})
},
If you look at the reference documentation for metadata.downloadURL it says:
deprecated
Use Reference.getDownloadURL instead. This property will be removed in a future release.
Determining the download URL for a file now requires another roundtrip to the server, so you'll need another then block for that:
firebase.database().ref('locations').push(location)
...
.then(key => {
const filename = payload.image.name
const ext = filename.slice(filename.lastIndexOf('.'))
console.log(payload.image)
return firebase.storage().ref('locations/' + key + ext).put(payload.image)
})
.then(fileData => {
return fileData.ref.getDownloadURL();
})
.then(imageUrl => {
return firebase.database().ref('meetups').child(key).update({imageUrl: imageUrl})
})
...
I have a json file and i fetched the data. However I cannot display it on the screen.
How can I display ? I get the data results in the console however I cannot reach the parametres like product name, price.
My code is below
index.html
<body>
<div id="products"></div>
<script src="/index.js"></script>
</body>
index.js
fetch("./data.json")
.then(response => {
return response.json();
})
.then(data => console.log(data));
showProducts = products => {
const showProductsDiv = document.querySelector("#products");
products.map(product => {
const productElement = document.createElement("p");
productElement.innerText = `product Name: ${product.name}`;
showProductsDiv.append(productElement);
});
}
I also share console results
You need to use your showProducts function.
Here is a sample code that will work for you too, but please, bear in mind, that I have used an example api. It's a bit different to yours that is why I have results array and name.first.
const url = 'https://randomuser.me/api/?results=10';
fetch(url)
.then((resp) => resp.json())
.then(data => {
return showProducts(data)
})
showProducts = products => {
const showProductsDiv = document.querySelector("#products");
products.results.map(product => {
const productElement = document.createElement("p");
productElement.innerText = `product Name: ${product.name.first}`;
showProductsDiv.append(productElement);
});
}
I am the new guy in the JS and reactJS.
I want to get info from API to an array. I made API that show all the info from my DB.
It looks like this :
const [tempNew, setTempNew] = useState([]);
const getAllWeatherCelsius = () => {
fetch('http://localhost:5000/weather')
.then(response => {
return response.json();
})
.then((jsonData) => {
let tmpArray = [];
for (var i = 0; i < jsonData.length; i++) {
tmpArray.push(jsonData.dayCelsius[i]) <---- here is the error
}
setTempNew(tmpArray);
})
}
Im want to collect all values from "dayCelsius" line into array.
What i need to change in this code ? Thank you :)
Can you provide more info about the error? But You can try using the map function like
const tmpArray = jsonData.map(r => r.dayCelsius);
You can use map function to return the dayCelsius value of each element and store them in the tmpArray.
let tmpArray = jsonData.map((el, i) => el.dayCelsius);
So, what I understand is that you are facing difficulty in just getting the dayCelsius value from the array of objects you fetch from your API.
It is difficult to make out what the problem is as more info about the error is required to see what is going wrong.
What I have done differently here is instead of the for-loop and jsonData.dayCelsius[i], I have used data.map((r,e) => r.dayCelsius).
const [temp, setTemp] = useState([]);
const getAllWeatherCelsius = () => {
fetch('http://localhost:5000/weather', {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
}
})
.then(response => {
return response.json();
})
.then((data) => {
const tempArray = data.map((r,e) => r.dayCelsius);
setTemp(tempArray);
})
.catch(err => console.log(err));
}
I hope it helps you, have a good day :)
I would like to add title to my JSON object, the structure I wish to achieve is:
{
"posts": [
{
"title": "put title here",
"upvotes": 1234,
"score": 1000,
"num_comments": 100,
"created": "16.05.2019 12:12",
},
]
}
I was able to fetch data and put it into array of 26 elements, everything is fine but I wish to somehow add this "posts:" to be above whole rest, here is my code:
fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json()
.then(async res => {
let posts = await res.data.children.map(el => {
let title = el.data.title;
let upvote = el.data.ups;
let score = el.data.score;
let comments = el.data.num_comments;
let created = el.data.created;
const allPosts = {title, upvote, score, comments, created}
postList.push(allPosts)
return postList
})
console.log(posts);
return posts
})
You might need to create the object like below
{propertyName:value}
const allPosts = {title:title,upvote: upvote,score: score,comments: comments, created:created}
postList.push(allPosts)
fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json())
.then(async res => {
console.log(res);
let posts = await res.data.children.map(el => {
let title = el.data.title;
let upvote = el.data.ups;
let score = el.data.score;
let comments = el.data.num_comments;
let created = el.data.created;
const allPosts = { title, upvote, score, comments, created };
let postList = [];
postList.push(allPosts);
return postList;
});
console.log({"posts": posts});
return {"posts": posts};
});
You can try out the following code.
fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json())
.then(res => ({
posts: res.data.children.map(el => ({
title: el.data.title,
upvote: el.data.upvote,
score: el.data.score,
comments: el.data.num_comments,
created: el.data.created
}))
}))
.then(posts => {
console.log(posts);
});
You can do it in this way:
fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json()
.then(async res => {
let posts = await res.data.children.map(el => {
return {
title: el.data.title,
upvote: el.data.ups,
score: el.data.score,
comments: el.data.num_comments,
created: el.data.created
}
})
const postObject = { posts }
console.log(postObject);
return postObject
})
Map function return value, in this way you get an object with key (posts) and values (an object with details).