Axios - How to read JSON response?
JavascriptReactjsSlimAxiosJavascript Problem Overview
Axios 0.17.1
.then(function (response) {
console.log(response);
//console.log(response.status);
//It is an error -> SyntaxError: Unexpected token u in JSON at position 0
console.log(JSON.parse(response.data.error));
console.log(response.data.error); //undefined.
The console.log of response is
> {data: "{"error":"Name must be entered with more than one … NULL↵
> ["isPipe":protected]=>↵ NULL↵ }↵}↵", status: 203, statusText:
> "Non-Authoritative Information", headers: {…}, config: {…}, …} config
> : {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout:
> 0, xsrfCookieName: "XSRF-TOKEN", …} data : "{"error":"Name must be
> entered with more than one character."}object(Slim\Http\Response)#32
> (5) {↵ ["status":protected]=>↵ int(200)↵
> ["reasonPhrase":protected]=>↵ string(0) ""↵
> ["protocolVersion":protected]=>↵ string(3) "1.1"↵
> ["headers":protected]=>↵ object(Slim\Http\Headers)#33 (1) {↵
> ["data":protected]=>↵ array(1) {↵ ["content-type"]=>↵
> array(2) {↵ ["value"]=>↵ array(1) {↵ [0]=>↵
> string(24) "text/html; charset=UTF-8"↵ }↵
> ["originalKey"]=>↵ string(12) "Content-Type"↵ }↵ }↵ }↵
> ["body":protected]=>↵ object(Slim\Http\Body)#31 (7) {↵
> ["stream":protected]=>↵ resource(59) of type (stream)↵
> ["meta":protected]=>↵ NULL↵ ["readable":protected]=>↵ NULL↵
> ["writable":protected]=>↵ NULL↵ ["seekable":protected]=>↵
> NULL↵ ["size":protected]=>↵ NULL↵ ["isPipe":protected]=>↵
> NULL↵ }↵}↵" headers : {content-type:
> "application/json;charset=utf-8"} request : XMLHttpRequest
> {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials:
> false, upload: XMLHttpRequestUpload, …} status : 203 statusText :
> "Non-Authoritative Information"
> proto : Object
JSON.parse(response.data) as well as response.data.error -> Both are giving error. How can i read the data?
Slimframework 3.
$data = array('error' => 'Name must be entered with more than one character.');
$newResponse = $response->withJson($data, 203);
return $newResponse;
Javascript Solutions
Solution 1 - Javascript
In Axios responses are already served as javascript object, no need to parse, simply get response and access data.
Solution 2 - Javascript
Assuming the response from the server looks like this:
{"token": "1234567890"}
Then in Axios you can access it like this:
console.log( response.data.token )
Solution 3 - Javascript
As already written, Axios already returns JSON by default. Just use response.data as simple JS object.
However, following insight might help others: I had an issue that Axios returned the response as a string. When investigated I discovered that the server returned an invalid JSON (it was a static file server). When fixed the JSON format, Axios used JSON instead of string again.
Solution 4 - Javascript
I had a similar format response as the one in console log and my issue was that my .json file wasn't properly formatted. I was missing a comma. Post your json file to have a look.
Solution 5 - Javascript
you can simply get it as following,
ex:
{
"terms": {
"title": "usage",
"message": "this is the usage message"
}
}
when the response look like this,you can get it using "response.data",and so on....
.then(response =>
console.log( response.data.terms.message)
Cheers !
Solution 6 - Javascript
axios by defualt convert response to JSON, you must use response.data
instead of response
export const addPosts = () => async (dispatch) => {
await axios('https://jsonplaceholder.typicode.com/todos/1')
.then(response => dispatch({type: postActionTypes.POSTS, payload: response.data}))}
Solution 7 - Javascript
Here is sample code,
try {
const res = await axios.get("/end-point");
console.log("JSON data from API ==>", res.data);
} catch (error) {
// handle error
}
Solution 8 - Javascript
For some reason, in my case the JSON was properly formatted but was returned as string anyway. With this workaround I solved the issue.
// ...
return await this.axios_instance.request<T>({
method,
url,
headers,
params,
transformResponse: (data) => JSON.parse(data), // <----------
data,
});
Simply put, I explicitly told to transform the response using JSON.parse. For some reason this worked, while other answers didn't.
This worked for me!! Hope it helps.
Solution 9 - Javascript
I had a similar problem. As others have pointed out, axios reads the json as a js object and you can easily move through the hierarchy to get your field data.
However, for me axios did not want to read the json as an object and instead returned a string. The cause was that there was a hanging comma at the end of the json due to a previous row deletion in the file. So the file content wasn't valid json, and axios simply returned a string. Remove the comma, everything worked.
I would suggest to check the json for any incorrect syntax.
Solution 10 - Javascript
So I came across this post in search of an answer to my question. "How to access data in a json file returned by an api." Nonetheless, what worked for me at the end of the day was an answer to a similar question on stackoverflow to which the link is https://stackoverflow.com/questions/48298890/axios-how-to-get-error-response-even-when-api-return-404-error-in-try-catch-fi.
However, here is the code I used to access my error codes returned by my backend api.
axios.get(/sanctum/csrf-cookie
).then(response => {
axios.post(api/register
, registerInfo)
.then(response => {
console.log('This is the response: ' + response.data.errors);
}).catch(error => {
console.log('This is the error: ' +
error.response.data.errors.name);
});
});
Solution 11 - Javascript
I had the same problem and I found that I was not reading data properly. Finally, I got a solution. try this.
my data was like:
response = [{"myname","Anup","age":23,"Education":"Graduation"}]
I was trying to retrieve data like(this was giving output undefined)
axios('https://apiurl.com')
.then((reponse)=>{
const recieved_Data=fetchdata.data;
console.log(recieved_Data.name);
})
Correct Approach:
axios('https://apiurl.com')
.then((reponse)=>{
const recieved_Data=fetchdata.data;
console.log(recieved_Data[0].name);
})
as you can see i have passed the index value of the array of my response recieved_Data[0].name And this gave me the correct output.
Vote me if this works for you.
Thanks!