Expo App JSON Parse Error Undefined Only on IOS - json

Hi I am building an app for IOS and Android using Expo and React Native
Now I have a weord issue,
I am using Fetch to get Json Data from the server, and the displaying it in a FlatList,
However I am having the weird issue where the data loads fine and populates the FLatlist when testing on android (Physical Devices, Appetize Simulator, Android Studio Emulator)
However when I am using a IOS device(Physical and Simulator)
I get a JSON parse error Undefined error and the the data does not load from the server I checked the json with jsonlint vlaidator and json data is fine,
here is my fetch use effect
useEffect(() => {
fetch('www.FAKEURLJsonDataURL')
.then((response) => response.json())
.then((responseJson) => {
//Successful response from the API Call
setDATA(responseJson.results);
setsearchDATA(responseJson.results);
console.log(responseJson.results)
})
.catch((error) => {
console.error(error);
});
}, []);
and now and example of how my Json data looks
{
"results": [{
"email": "FakeEmail#Fake.com",
"id": "1",
"name": "Fake Name",
"customerid": "40683372",
"contacttel": "",
"contactmobile": "0123 456 6899",
"contactperson": "Fake Name"
}]
}
I noticed that the json parse error happens on the "name" items in the json, But i checked and it all looks fine
there are alot of enteries in the json data but that is how they look when you recieve them from the server
As i said above the code works, on android perfectly, but if i try to run it on IOS, then I get a Json Parse error

Related

Postman: POST request of nested JSON via form-data not working (while via raw-data ok)

I want to POST the following JSON-object via Postman:
{
"title": "test_title",
"date": "2021-12-31",
"attachments": [
{
"name": "test_attachment"
}
]
}
This works perfectly fine, when using Postman's raw input form for the request-body: I get a "201 Created"-response back.
However, when using the form-data to POST the data, I get the error "Invalid data. Expected a dictionary, but got str." (see also screenshot below) What am I doing wrong here? I tried all kind of other versions to enter the attachment-key:value pair but nothing worked so far
I managed to make it work! (note: I added some additional fields compared to the screenshot in question. See below for details:
You did nothing wrong.
If you want to make a request with json object, then you go with raw type (json) in postman.
If you want to upload file, then you use form-data
One more thing, status 201 means the request is succeed, your object has been created.
var express = require('express')
const multer = require('multer')
const upload = multer()
var app = express()
app.use(express.json());
app.post('/test',upload.none(), function (req, res, next) {
res.send(req.body)
})
app.listen(80, function () {
console.log('web server listening on port 80')
})
Above is a sample endpoint which works with both form-data and json , just do a post to http://localhost:80/test with both form data and raw json
you can see both will get parsed correclty
APIs are just abstraction , its like a function that takes in many attribute, how you parse it depends on the implementation ( how the api function is written) .
so answer is "Talk to the developer" on how the API is implemented and what it is supporting
I'm having issue in placing json into form format the way Daniel did in Postman. Need help in figuring out what is it required to place the cascaded json objects into form data format. Please see here that I'm trying to accomplish.
JSON Format (to be filled into Postman form-data section:
{
"primary_object": {
"child_object_1": [{"id": 12345678, "value": "abc"},{"id": 87654321, "value": "xyz"}],
"child_object_2": [
"first_val",
"second_val"
]
}
}

Cypress intercept API JSON response and extract URL

My web app sends an API POST request to create an application and returns JSON response. I want to access one particular JSON object from that response.
My JSON starts like this
[
{
"status_code": 201,
"body": {
"created": "2021-01-28T00:00:00Z",
"modified": "2021-01-28T00:00:00Z",
"id": "a2d86d17-9b3c-4c4d-ac49-5b9d8f6d6f8f",
"applicant": {
"id": "07f1e1d3-0521-401b-813e-3f777f2673c6",
"status": "Pending",
"first_name": "",
"last_name": "",
"URL": "some onboarding url"
And I wanna take that URL in the JSON response and visit it later in my cypress automation script.
Notice that the JSON repsonse starts with a square bracket not a curly bracket, which means, the whole response is an object, I assume?
My cypress script looks like this
cy.contains('button', 'CONTINUE').click()
cy.EmailGen('candidate').then(email => {
cy.get('#emails\\[0\\]').type(`${email}`)
cy.wrap(email).as('candidateEmail')
})
//writing intercept here, before the Send application button, which triggers the POST req.
cy.intercept('/hr/v1/applications/invite').as('getURL')
cy.get('button').contains('SEND APPLICATION').click({ force: true })
//waiting on the alias of intercept and using interception to print objects from response
cy.wait('#getURL').then((interception)=> {
cy.log(interception.response.body.applicant.URL)
})
cy.Logout()
The script executes with no errors. Just that nothing is logged in the cy.log statement. Below is the screen.
I also tried using another method as given below.
cy.intercept('/hr/v1/applications/invite',(req) => {
req.reply((res=> {
expect(res.status_code).to.equal('201')
expect(res.body.applicant.status).to.equal('Pending')
}))
})
In this case, I get a assert error embedded with the request and response along with some other stuff which I am unable to understand.
The complete error goes something like this...
"expected The following error originated from your test code, not from Cypress.\n\n > A response callback passed to req.reply() threw an error while intercepting a response:\n\nexpected undefined to equal '201'\n\nRoute: {\n "matchUrlAgainstPath": true,\n "url": "/hr/v1/applications/invite"\n}\n\nIntercepted request:{} Intercepted response: {} When Cypress detects uncaught errors originating from your test code it will automatically fail the current test. to include window.zE is not a function"
Its a bit weird to read this..
My application sometimes throws this exception, which I have handled using following code.
cy.on('uncaught:exception', (err, runnable) => {
expect(err.message).to.include('window.zE is not a function')
done()
return false
})
I really hope I have explained everything here. Please, help a noob.
Regards
As Richard Matsen suggested in the comments,
I used console.log(interception.response) and checked the console output in the browser controlled by Cypress.
I Noticed that the response json structure was something different than what I got in the network tab of developers tools, while using the web app.
The response was something like below...
{headers: {…}, url: "https://example.com/hr/v1/applications/invite/batch/", method: null, httpVersion: "1.1", statusCode: 200, …}
body: Array(1)
0:
body:
applicant: {id: "c6b2d686-d4f3-483e-abc8-e4641c365845", status: "Pending", first_name: "", last_name: "", email: "qa2+candidate879#example.com", …}
applicant_status: "NONE"
applicant_status_label: "None"
created: "2021-01-29T00:00:00Z"
get_applicant_status_display: "None"
id: "ad2939f5-c8ab-490a-a9e1-b0474de69e2c"
URL: "some url"
This made me modify the json traverse to
interception.response.body[0].body.applicant.URL
If others have a neat way to handle this, please let me know!

How to load json file?

I am just trying to load JSON file into my react project. I did it like this:
fetch(dane).then(response => {
console.log(response);
return response.json();
}).then(dane => {
console.log(dane);
}).catch(err => {
console.log("Error Reading data " + err);
});
and I imported this file into project:
import data from "./data.json";
but I am getting error like this:Unexpected token < in JSON at position 0
How can I fix it?
If I am asking about something very stupid, just sorry.
The json file is in src folder.
You would only use fetch to get the data from an API and assign the response to a variable that you can call.
Since you are using a mock json response stored in a file, you can do the following.
Example:
A file called data.json containing the following.
{
"name": "John",
"age": "47",
"role": "admin"
}
Can be imported via:
import data from "./data.json"
Then used in your component however you wish.
<h1>Hello {data.name}.</h1>
<h2>Logged in as: {data.role}</h2>
Or if used outside of the render, like in a function:
console.log(data.role)
Also, Unexpected token < in JSON at position 0 seems like your JSON is improperly formatted.
The JSON file should only contain valid JSON data, as shown in my basic example above.

JSON Parse error: Unexpected identifier "Not"

I am working through the react-native tutorial at http://facebook.github.io/react-native/docs/tutorial.html#fetching-real-data and after adding the function
fetchData: function() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
movies: responseData.movies,
});
})
.done();
},
to the AwesomeProject object and then reloading the iOS simulator, I get the error JSON Parse error: Unexpected identifier "Not". Since I have not written any JSON, I do not know where this error could be coming from.
I had missed a character in REQUEST_URL. Therefore the request for that URL was returning a 404 Not Found, of which the first non-json token was of course, Not. I determined this by running curl on the url, but you can also check it by visiting the url in a browser.

JSON API result format

Folks,
Designing my first API in Node.JS using restify.js. My background is not webapis, pardon my amateur questions. In any case, I would like to have the res.send(data); responses to comply with the http://jsonapi.org/format/ so that my mobile application can start utilizing the api calls. At the moment if you were to call my api, it would return data in the following format:
{"Count":1,"Items":[{"dbsource":{"S":"foo"},"id":{"S":"5002820"},"name":{"S":"fnameblah,lnameblah"},"expiration":{"S":"06/13/2015"},"type":{"S":"bar"}}]}
Actually what you see above is just a return of a DynamoDB Query call.
So the question is... do you use a special library that you can pass data to, which would format and return the data in JSON format. Which in turn you can return it via res.send(data) to the clients, or is it up to us to make 'data' JSON compliant, then return it? At the end of the day we all want the results to look like:
{
"posts": [{
"id": "1",
"title": "Rails is Omakase",
"links": {
"author": "9",
"comments": [ "5", "12", "17", "20" ]
}
}]
}
Thanks!
In server side, stringify JSON object,
//...
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(data)); //data is JSON object
res.end();
In client side, parse JSON string accordingly.
EDIT: Corrected response content type.
JSON data from server should be a JSON string
You have to parse it back the JSON format in client.
JSON.parse(string); // return JSON object