Axios - How to read JSON response?
Asked Answered
O

12

74

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;
Oneil answered 2/1, 2018 at 14:34 Comment(4)
SyntaxError: Unexpected token u in JSON at position 0Oneil
Check console.log(response.data) and see what the format is of the data object. Looking at your example output it looks like there is too many quotes " - data: "{"error":"Name must be entered... - this: "{"error":" looks strangeDromous
Verify whether the response you receinved is a valid JSON. If it is valid, axios will parse it to a JSON object. otherwise it will return you a plain string object.Kearse
do like this for axios .then((response)=> JSON.stringify(response.data)) .catch((error)=> JSON.stringify(error.response.data))Zorine
R
88

In Axios responses are already served as javascript object, no need to parse, simply get response and access data.

Remanence answered 2/1, 2018 at 14:38 Comment(6)
console.log(response.data.error); //undefined - I can log response.data But response.data.error is undefined. unable to use JSON.parse - it is giving me error.Oneil
This means that response.data EXISTS but do not have "error" key , can you post the output of response.data ? Usually when response.error is undefined simply means that the axios response has no errors.Velure
the yellow color box (content) is the console.log for response received from slimframework. - Please check i updated again.Oneil
can you post RAW output ? ES: console.log(response). If you are using chrome, I mean not the "preview" tab in network, but "response" tab.Velure
you should provide an example instead of saying just do itPerdu
This top rated answer is missing some info. Axios only converts valid JSON automatically. If the JSON contains an error Axios quietly fails the JSON parse and just serves a string.Witchhunt
M
33

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 )
Miltiades answered 29/7, 2020 at 12:20 Comment(0)
A
9

This happened to me because I wrote

import { Axios } from "axios"; // named export: problem
const instance = new Axios({ baseURL: "#####" }); // new Axios: problem

When it was supposed to be

import axios from "axios"; // default export: no problem
const instance = axios.create({ baseURL: "#####" }); // axios.create: no problem

Credits: https://github.com/axios/axios/issues/3419#issuecomment-1015921836

Augustaaugustan answered 21/3, 2023 at 14:9 Comment(0)
W
7

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.

Wassail answered 31/1, 2021 at 6:54 Comment(1)
I was also using a mocked JSON response, and it had an extra closing comma which was causing the parsing issuePlunder
M
5

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 !

Mitchum answered 10/4, 2021 at 21:56 Comment(0)
P
3

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.

Pellitory answered 11/11, 2018 at 14:17 Comment(0)
L
3

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.

Lever answered 2/11, 2021 at 20:31 Comment(1)
I made the same experience with django JSON serialized object from a query. dict object from django works without JSON.parse.Kironde
R
2

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}))}
Relax answered 4/12, 2020 at 8:9 Comment(0)
M
1

Here is sample code,

try {
  const res = await axios.get("/end-point");
  console.log("JSON data from API ==>", res.data);
} catch (error) {
  // handle error
}
Matchmark answered 24/8, 2021 at 12:28 Comment(0)
C
0

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.

Crossbar answered 24/8, 2021 at 12:21 Comment(0)
S
0

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!

Stereotypy answered 18/3, 2022 at 18:5 Comment(0)
M
-1

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 Axios. How to get error response even when api return 404 error, in try catch finally.

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

Mikkimiko answered 3/12, 2021 at 1:18 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Puma

© 2022 - 2024 — McMap. All rights reserved.