Check if json contains a key in react-native - javascript

I'm kinda new to react-native (and javascript in general). At the press of a button, I want to search a json api for a certain key (in this case a movie).
For example, heres the api https://facebook.github.io/react-native/movies.json
Now on the press of a button, I want to check if the api contains a movie named "The Matrix".
The networking tutorial states that to fetch the json, you need the following method :
function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}
This returns a json object, but how would one query this object to check if it contains a movie named "The Matrix" for example?
Any help would be greatly appreciated.

What you would do is use Array.prototype.find() for movies array in the json response and check for the value
function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}
//from where you are calling getMovies
getMoviesFromApiAsync()
.then(response => {
var data = response.find((movie) =>
movie.title.toUpperCase().indexOf('THE MATRIX') > -1
)
console.log(data)
if(data) {
console.log('found');
}
})
The other options are to use
Array.prototype.some()
var data = response.some((movie) => movie.title.toUpperCase().indexOf('THE MATRIX') > -1)
Array.prototype.filter()
var data = response.filter((movie) => movie.title.toUpperCase().indexOf('THE MATRIX') > -1)

Related

How can I console.log an individual attribute from a JSON payload object?

I am trying to console.log some JSON values from an OpeanSea api call payload.
I can successfully hit the end point as seen in the console
when I run this:
await fetch(`https://api.opensea.io/api/v1/collections?asset_owner=${currentAccount}&offset=0&limit=300`, options)
.then(response => response.json())
.then(response => console.log("collection owned by current address", response))
but when I try to log only one attribute from the response object:
await fetch(`https://api.opensea.io/api/v1/collections?asset_owner=${currentAccount}&offset=0&limit=300`, options)
.then(response => response.json())
.then(({ assetts }) => {
assetts.forEach((attributes) => {
console.log(attributes.name)
})
})
I see
TypeError: Cannot read properties of undefined (reading 'forEach')
Is
assetts
an arbitrary name to iterate through? I think this is what i dont understand
You should know the structure of json and target the required attributes. Like in your case its collections array which is array of object and each object contains name key so you can target key like:
await fetch(`https://api.opensea.io/api/v1/collections?asset_owner=${currentAccount}&offset=0&limit=300`, options)
.then((response) => {
return response.json();
})
.then((assetts) => {
assetts.collections.forEach((attributes) => {
console.log(attributes.name);
});
})
.catch((error) => {
console.log({ error });
});
In your first then block you should have to return response after parsing it, if you want to use the parsed data in next then block.
Tip: It is a good practice if you also handle error by putting catch block after then block.

Checking if JSON object from promise is null

I had another similar topic open and it received negative response. I am facing a legitimate issue here and assure you I have researched this extensively. I believe my real issue is probably the syntax as I am not a proficient JS coder. This has been an ongoing struggle for an embarrassing 2 weeks now. I have the following:
fetch('https://example.com/api/submission?data.dateOfService=' + data.dateChanger + '&select=data.endingPettyTotal')
.then(response => response.json())
.then(data => instance.setValue(data[0].data.endingPettyTotal));
I am trying to look at the JSON object and if it's length is zero, set my data.engingPettyTotal to '0'. If not zero, then set it equal to the JSON object's value, like I have above.
It seems I should be able to accomplish this by checking the response.json().length, something similar to this
fetch('https://example.com/api/submission?data.dateOfService=' + data.dateChanger + '&select=data.endingPettyTotal')
.then(response => {
if(response.json().length === 0) {
console.log("empty")
return 0;
}
else {
console.log("not empty")
return
})
.then(data => instance.setValue(data[0].Balance));
}
Unfortunately this does not seem to be working either. Again, assuming I have just messed up syntax or something but then again this async stuff is confusing. Also assume this could be done with lodash (isEmpty or isNull).
response.json() returns a promise that resolves with the server sent data
Do your check in the second then()
fetch('https://example.com/api/submission?data.dateOfService=' + data.dateChanger + '&select=data.endingPettyTotal')
.then(response => {
if(!response.ok){
return Promise.resolve(0)// or just throw error
}
return response.json())
}).then(data =>
// if not array or empty array set as zero
const val = (Array.isArray(data) && data.length) ? data[0].Balance : 0;
instance.setValue(val);
})
response.json() returns a Promise object, try:
fetch('http://your.url')
.then(response => response.json())
.then(data => instance.setValue(data.length && data[0].Balance));
or if you don't want to set value if data.length equals 0:
fetch('http://your.url')
.then(response => response.json())
.then(data => data.length && instance.setValue(data[0].Balance));
it's hard to tell exactly what your parameter's names are... are they "data.dateofService" on the server Side? (assuming below that it is just 'dateOfService')
sending data via json/FormData have different handling on the PHP side.
an alternate to sending json - is new FormData()... and append('key',"value");
and instead of jsonData attach the formData to the body attribute.
const sendData = {
dateOfService: data.dateChanger,
select:data.endingPettyTotal
}
const jsonData = JSON.stringify(sendData);
const options = {
method:"POST",
body: jsonData
}
fetch('https://example.com/api/submission',options)
.then(response => response.json())
.then(data=>
{
if(data.length == 0) {
console.error("no data")
}
else {
console.log("not empty")
instance.setValue(data[0].Balance);
}
});
You're not returning the a promise that returns the JSON from your first callback function.
Put the check in the second .then().
fetch('https://example.com/api/submission?data.dateOfService=' + data.dateChanger + '&select=data.endingPettyTotal')
.then(response => response.json())
.then(data => {
if (data.length == 0) {
console.log("empty");
} else {
console.log("not empty");
instance.setValue(data[0].data.endingPettyTotal));
}
});

Parse API responce with javascript

I have got the response from the JSON API, but I don't know how to parse it, it just comes back with an error, I don't know enough about it to figure it out, it returns:
(node:36308) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token o in JSON at position 1
var fetch = require('node-fetch');
fetch('https://sv443.net/jokeapi/v2/joke/Any', function(res){
if (res.ok) {
return res;
} else {
console.log(res.statusText);
}
})
.then(res => res.json())
.then((json) => {
var parsedData = JSON.parse(json)
console.log(parsedData.joke);
});
You just need to do the following to access the delivery.
fetch("https://sv443.net/jokeapi/v2/joke/Any?type=single")
.then(response => {
return response.json();
})
.then(json => {
// likely to be json.delivery but cannot
// confirm until rate limits have been lifted
console.log(JSON.stringify(json));
})
.catch(err => {
console.log(err);
});
Try this:
fetch('https://sv443.net/jokeapi/v2/joke/Any', function(res){
if (res.ok) {
return res;
} else {
console.log(res.statusText);
}
})
.then(response => response.json())
.then(data => console.log(data));
You are already parsing it with res.json(). It returns an object (in promise) which can be accessed directly. Depending on a type prop you may have different props to check for. For example twopart joke will have setup: question, and delivery: answer

retrieving json data by a key

const username = 'merMan';
fetch("./datz.json")
.then(response => response.text())
.then((response) => {
console.log(response);
})
my data response looks like below, still having a difficult time simply getting a user specific data. My response data outputs like below. I have tried using find, but always returns find is not a function, response[username] does not work either.
[{"mermAn":{"baseMapId":"459cc334740944d38580455a0a777a24","customBaseMap":"","zoomn":"5","orient":"0","centLon":"-93.69999999999843","centLat":"38.64999999999935"},
{"catWoman":{"baseMapId":"459cc334740944d38580455a0a777a24","customBaseMap":"","zoomn":"5","orient":"0","centLon":"-93.69999999999843","centLat":"38.64999999999935"},
{"Riddler":{"baseMapId":"459cc334740944d38580455a0a777a24","customBaseMap":"","zoomn":"5","orient":"0","centLon":"-93.69999999999843","centLat":"38.64999999999935"}}]
You need to parse the response after response.text(), like:
fetch("./datz.json")
.then(response => response.text())
.then((response) => {
try {
const parsedArray = JSON.parse(response);
console.log(parsedArray);
} catch (error) {
// response could not be parsed
}
})
Use .json() instead of .text()
const username = 'merMan';
fetch("./datz.json")
.then(response => response.json())
.then((users) => {
console.log(users.find(x => typeof x[username] !== "undefined"));
})

Fetch res.json() Attempt to invoke intergace method 'java.lang.String...'

I'm trying to convert a response from fetch function into json format but when I do so I get an error Attempt to invoke interface method 'java.lang.string com.facebook.react.bridge.ReadableMap.getString(java.lang.String)' on a null object reference.
Here is my code snippet with fetch function:
export const fetchAllUsers = () => {
fetch('http://192.168.1.103:3000/api/userData')
.then(res => {
res.json();
//console.warn('res keys = ' + Object.keys(res))
})
}
If comment back the row with console.warn I see the following "res keys = type, status, ok, statusText, headers, url, _bodyInit, _bodyBlod, bodyUsed".
bodyUsed = false
status = 200
type = default
Why I can't convert a response into json format? Or is there any another way to do so?
UPDATE
I've added the second then but I still get the error and the console.warn('res is json') is not running:
export const fetchAllUsers = () => {
fetch('http://192.168.1.103:3000/api/userData')
.then(res => {
res.json();
//console.warn('res keys = ' + Object.keys(res));
})
.then(res => {
console.warn('res is json');
console.warn(res);
})
}
UPDATE_2
I've run fetch function with another url but still got the problem. It seems like .json() causes the error. When I'm trying to console the result of fetch in the first .then() I get json object with type, status etc keys.
export const fetchAllUsers = () => {
fetch(`http://${localIP}:${port}/api/userData`)
//.then(res => res.json())
.then(json => console.warn('JSON: ' + json))
.catch(e => console.warn('ERROR: ' + e))
}
UPDATE_3
Forgot to mention that I'm creating an Android app with React Native. For testing I'm using a physical smartphone. Chrome version there is 73.0.3683.
I've replaced my fetch query with the following:
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json));
But still get the same error.
When I run it in https://jsfiddle.net/ it works. So the reason is hidden inside the code execution on a smartphone.
There must be more context to your problem; see the below snippet. This clearly works.
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json));

Categories

Resources