How to parse an external json file in React? - javascript

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'));
}, []);

Related

How to call multiple APIs using loop

Hi I'm making SPA react program
I have some question
I want to know how can I use this JSON data HackNews
const [storyIds, setStoryIds] = useState([]);
const list = [];
useEffect(() => {
Top_API().then((res) => {
this.res = res.data.slice(0, 3);
this.res.forEach((ele) => {
axios
.get("https://hacker-news.firebaseio.com/v0/item/" + ele + ".json")
.then((res) => {
list.push({
id: res.data.id,
title: res.data.title,
url: res.data.url,
user: res.data.by,
score: res.data.score
});
setStoryIds(list);
});
});
});
}, []);
this is my code i want to print this api data
I print JSON data like this
{JSON.stringify(storyIds[0])}
This code works well. However, from the storyIds[1] arrangement, it is not visible on the screen. I checked that it was output from the console.
And when I go to a different page,
If I output the contents of my code array, an error occurs that the array cannot be found when you return to the page.
ex)
{JSON.stringify(storyIds[0].title)}
If you write like the code above, an error occurs that the array is not defined.
I've been trying to solve this situation for three days now without a proper solution.
The code that you print on the screen is as follows.
<div className="n1">
<a href={JSON.stringify(storyIds[0])}>
{JSON.stringify(storyIds[0])}
</a>
<br />
by: {JSON.stringify(storyIds[0])}
</div>
<div className="n2">{JSON.stringify(storyIds[1])}</div>
<div className="n3">{JSON.stringify(storyIds[2])}</div>
</div>
the data look's like
[{"id":30186326,"title":"Facebook loses users for the first time","url":"https://www.washingtonpost.com/technology/2022/02/02/facebook-earnings-meta/","user":"prostoalex","score":994},{"id":30186894,"title":"In second largest DeFi hack, Blockchain Bridge loses $320M Ether","url":"https://blockworks.co/in-second-largest-defi-hack-ever-blockchain-bridge-loses-320m-ether/","user":"CharlesW","score":400}]
how can I print this API response my screen?
You need to use async await with Promise.all for waiting for response from API
useEffect(() => {
Top_API().then(async (res) => {
this.res = res.data.slice(0, 5);
Promise.all(
this.res.map(async (r) => {
return await axios.get(
"https://hacker-news.firebaseio.com/v0/item/" + r + ".json"
);
})
).then((resolved) => {
resolved.map((resolve) => {
list.push({
id: resolve.data.id,
title: resolve.data.title,
url: resolve.data.url,
user: resolve.data.by,
score: resolve.data.score
});
});
setStoryIds(list);
});
});
}, []);

there is some error when i using url and parse

when i use this code in goole console it works like this
but when i use same code in react-native there is only data in _url like this
I want to get values ​​from searchParams.
this is my code
const Kakao = ({navigation}) => {
useEffect(() => {
Linking.addEventListener('url', async ({url}) => {
const urll = new URL(
'demo://app?accessToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6bnVsbCwicHJvdmlkZXIiOiJrYWthbyIsImlhdCI6MTYxODM5NDgwNX0.GfYs5rt0tjBrUmNvNIT6Bn_7TlJfY7zF9NxvkdqeTE0/',
);
console.log('urll.search', urll.search);
});
return () => Linking.removeEventListener('url');
}, []);
how can i fix my code to get a urll.search data ???

Display API JSON response in template - Angular

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?
})();

How to delete break lines on JSON between rows when printing it in a web browser in Javascript?

In Javascript I have to print in the document a JSON with some data from MySQL database and I want to remove the break lines but I cannot achieve it.
I get the data through node.js and I use express.js for printing it on a web browser.
This is the result:
As you can see, there is a break line between both rows and I want to remove it since it is causing issues when I try to read the JSON on the android application I am building.
I have tried to search on internet about how to achieve it, most answers were about using str.replace(/\r?\n|\r/g, '') but it did not work in my case.
This is the JS code I currently have:
var dbData = '<%-usersList%>';
dbData = JSON.parse(dbData.replace(/\r?\n|\r/g, ''));
document.write(JSON.stringify(dbData));
And this is how I pass the data from node.js:
app.get('/dbJSON', function (req, res) {
getDBData().then((data) => {
res.render('./dbJSON.ejs', {
usersList: JSON.stringify(data.usersList)
});
});
});
This function calls the js file that gets the data from the db:
function getDBData() {
const users = new Promise((resolve, reject) => {
dbConnection
.getUsers()
.then(data => {
resolve(data)
})
});
const groups = new Promise((resolve, reject) => {
dbConnection
.getGroups()
.then(data => {
resolve(data)
})
});
const frmTexts = new Promise((resolve, reject) => {
dbConnection
.getFrmTexts()
.then(data => {
resolve(data)
})
});
return Promise.all([users, groups, frmTexts])
.then(data => {
return {
usersList: data[0],
groupsList: data[1],
frmTextsList: data[2]
}
});
}
Result of printing out data.usersList (in node.js):
Edit: Fixed! The reason of why I wanted to delete the break lines was because I had issues with parsing the JSON on Android Studio but I have just figured out it was due to I did not add the http:/ in the url string (my bad). Now my android app is working.
#Adrian2895,
Simply convert it to string and this will remove new-line/carriage-return. And also the above code is working fine (which I referred to use deep-cloning to remove any attribute).
You can use the concept of deep cloning to get rid of unwanted attributes from JSON obj.
var rawData = [{
'iduser':1,
'user':'XXX',
'password': 'XXX123',
'groups_idgroup': 1,
'idgroup':1,
'name': 'James'
},
{
'iduser':9,
'user':'XXX',
'password': 'XXX123',
'groups_idgroup': 2,
'idgroup':2,
'name': 'James'
}];
rawData.forEach( function(item, index){
rawData[index] = Object.assign({}, item, {'user':undefined, 'password':undefined, 'name': undefined} );
console.log(JSON.stringify(rawData));
Output:-
[{"iduser":1,"groups_idgroup":1,"idgroup":1},{"iduser":9,"groups_idgroup":2,"idgroup":2}]

How to extend AdonisJS Response class?

When a user creates a post in my RESTful application, I want to set the response status code to 201.
I followed the documentation and created start/hooks.js as follows:
'use strict'
const { hooks } = require('#adonisjs/ignitor')
hooks.after.httpServer(() => {
const Response = use('Adonis/Src/Response')
Response.macro('sendStatus', (status) => {
this.status(status).send(status)
})
})
Now in my PostController.js, I have this:
async store( {request, response, auth} ) {
const user = await auth.current.user
response.sendStatus(201)
}
But I am getting 500 HTTP code at this endpoint.
What am I doing wrong?
I noticed when I run Response.hasMacro('sendStatus') I get false.
In fact adonis already have this out of the box for all response codes...
Just write response.created(.....).
You can also use for example: .badRequest(), .notFound(), etc...
More info on: https://adonisjs.com/docs/4.1/response#_descriptive_methods
I solved this problem yesterday:
hooks.after.httpServer(() => {
const Response = use('Adonis/Src/Response')
Response.macro('sendStatus', function (status) => {
this.status(status).send(status)
})
})

Categories

Resources