Display API JSON response in template - Angular - javascript

I want to display data on my website from JSON file from URL.
I work on Angular and I've create a HttpClient in my component. Code below show all document in console, so here is my question.
let resp = this.http.get("https://spreadsheets.google.com/feeds/cells/1w2vpgbwImaQGCbpMqZ3P0NC93tuVved0oOFc9Zr22dU/1/public/full?alt=json");
resp.subscribe((data)=>console.log(data));
Can I show a specify elements from this JSON file?
I want to display data from: feed -> entry -> gs$cell -> $t on my website.
How I should start, what I need?
I have add a picture how the JSON array looks and what elements I want to get and show on my website.

Store API response in a class variable i.e data, assume sample data
data = {
feed: {
entry: [
{ gs$cell: { $t: 'Nazwa' } },
{ gs$cell: { $t: 'pazwa' } },
{ gs$cell: { $t: 'shuzwa' } }
]
}
}
Accessing directly in template
<div *ngFor="let d of this.data.feed.entry">{{d.gs$cell.$t}}</div>

It seems to me that your problem is how to extract the data.
I can't use your HttpClient so I will be using fetch API for demonstration.
async function getData() {
const endpoint =
"https://spreadsheets.google.com/feeds/cells/1w2vpgbwImaQGCbpMqZ3P0NC93tuVved0oOFc9Zr22dU/1/public/full?alt=json";
// const json = await http.get(endpoint);
const response = await fetch(endpoint);
const json = await response.json();
const { feed } = json;
const { entry: feedEntries } = feed;
return feedEntries.map((entry) => {
const { gs$cell } = entry;
const { $t } = gs$cell;
return $t;
});
}
(async () => {
const data = await getData();
console.log(data);
// do whatever you wan't with the data, use it on your template maybe?
})();

Related

getServerSideProps not fetching data despite of running it inside the page

hello i am trying to fetch data inside by next app using getServerSideProps which is just not fetching the data , the data returns either an empty object or undefined inside the console i don't know what is wrong with the app , i have tried other next js data-fetching methods too and results are same
export const getServerSideProps = async () => {
// Fetch data from external API
const res = await fetch(`https://rickandmortyapi.com/api/character`)
const data = await res.json()
console.log(data)
// Pass data to the page via props
return { props: { data } }
}
I threw that code into my current project and it works.
interface Props {
data: {
info: any;
results: any[];
}
}
const Page: NextPage<Props> = ({ data }) => {
console.log(data); // { info: {...}, results: Array(20)}
// ...
}
export const getServerSideProps = async () => {
const res = await fetch('https://rickandmortyapi.com/api/character');
const data = await res.json();
return { props: { data } };
};

Get failed rows when using Mongoose Model.insertMany

We are trying to import a csv with around 30.000 lines of data into a MongoDB database using Mongoose. We have created a model with some validators so only correct rows will be added to the database.
First we read the csv with papaparse and create an array out of it. Next we insert the data into the database with the mongoose Model.insertMany method. To continu inserting data when a row fails we use the option ordered: false.
This all works but we are looking for a way to collect the failed rows so we can check why a row didn't get passed the validation.
Is there a way to get the failed rows with the insertMany method?
...
const readCSV = async (filePath) => {
const csvFile = fs.readFileSync(filePath);
const csvData = csvFile.toString();
return new Promise(resolve => {
Papa.parse(csvData, {
header: true,
transformHeader: header => header.trim(),
complete: results => {
console.log('Complete', results.data.length, 'records.');
resolve(results.data);
}
});
});
};
const start = async () => {
try {
await connectDB(process.env.DATABASE_URL);
const parsedData = await readCSV(csvFilePath);
const response = await Company.insertMany(parsedData, { ordered: false });
console.log(response);
} catch(error) {
console.log(error);
}
}
start();

getStaticProps Does not return any data to the pages on Next.JS

I'm trying to fetch a data from my hosted database. The database itself are working (I have checked it from the swagger app) but no data is shown when it is called from API form.
import React from 'react';
export const getStaticPaths = async () => {
const res = await fetch('https://[server]/course');
const data = await res.json();
const paths = data.result.map(course => {
return {
params: { id: course._id.toString() }
}
})
return {
paths,
fallback: false
}
}
export const getStaticProps = async (context) => {
const id = context.params.id;
const res = await fetch('https://[server]/course/' + id);
const data = await res.json();
return {
props: { course: data }
}
}
const Details = ({ course }) => {
return (
<div>
<h1> { course.course_name } </h1>
<h1>a</h1>
</div>
);
}
export default Details;
The code is in the pages folder. I followed a tutorial on youtube from "netninja" and when I tried it on his code it works. I read somewhere that it won't work on components but I already put it on the pages but it still does not return anything.
Is there anything I can do ?
I got the answer. After checking console.log on the data. Looks like the data is on another array which is called result. so i needed to call the data from course.result.course_name. So the Answer is just to check console.log every once in a while. Shout out to juliomalves for pointing that out

How to parse an external json file in React?

I want to parse an external JSON file into my react app.
Here, I created a working example of what I want in Codesandbox.io:
https://codesandbox.io/s/morning-tdd-we2v3?file=/src/App.js
In this example, I am using some JSON data inside of the application but wanted to parse this data from an outside source file here: https://raw.githubusercontent.com/Forschung/AmbeentData/main/modems.json
I tried some ways but could be successful.
Best
Your JSON data format is invalid and that the reason for this problem.
you can fetch data as pure text and then fix them locally like this.
demo
const [data, setData] = useState([]);
useEffect(() => {
async function getData() {
fetch(
"https://raw.githubusercontent.com/Forschung/AmbeentData/main/modems.json"
)
.then(function (response) {
return response.text();
})
.then(function (txt) {
let d = txt.replace(/Brand/g, `"Brand"`);
d = d.replace(/Model/g, `"Model"`);
d = JSON.parse(d);
setData(d);
});
}
getData();
}, []);
'json file is wrong' the correct one should be
"key": "value"
You did this as
key: "value"
Wrong Json file
[
{ Brand:"Actiontec", Model:"GT784WNV" },
{ Brand:"Actiontec", Model:"MI424WR" },
{ Brand:"AirTies", Model:"Air 4450" }
]
Must Have Json File
[
{
"Brand":"Actiontec",
"Model":"GT784WNV"
},
{
"Brand":"Actiontec",
"Model":"MI424WR"
},
{
"Brand":"AirTies",
"Model":"Air 4450"
}
]
The answer to the second question is that you can make this request very simply using the axios library. I'll leave the sample code and the live example.
Proje Test Link
Sample code
useEffect(() => {
axios(
"json link"
)
.then((res) => setDatas(res.data))
.catch((e) => console.log(e))
.finally(() => console.log('finally'));
}, []);

Nuxt.JS: How to get post parameter data in a vue file

I am integrating paytm payment gateway in my nuxt js project. Buy I am
unable to get post data with which paytm is redirecting to my callback
url.
Since asyncData gives you access to req and res (see https://nuxtjs.org/guide/async-data/#use-reqres-objects), you can parse the body to get POST parameters. I found this solution out there, so I didn't try it out. In fact, it should be better to use a Middleware to parse this and load the middleware in that page.
<script>
export default {
asyncData ({ req, res }) {
if (process.server) {
const qs = require('querystring')
let body = ''
let temp = ''
let paymentData = ''
while(temp = req.read()) {
body += temp
}
paymentData = qs.parse(body)
return { data: paymentData }
}
},
data () {
return {
paymentData: '',
}
},
mounted () {
console.log(this.paymentData)
}
</script>

Categories

Resources