0
votes

I'm not familiar with JavaScript and Axios, so any help will be great :)

My request from Axios to URL has this response.

data: '{"id":"test1", "cool":"test2"}'

When trying JSON.parse like this

const buildArray = (await axios(config)).data
let toJSON = JSON.parse(buildArray)

It gives me an error

Unexpected token  in JSON at position 0

Here it is my code and what I'm trying to do. For each Axios data response I want to add it to an array item and return it.

async function buildList(items, token){
try {
    const list = []
    let config = ''

    for (item of items.items) {
        config = {
            method: 'get',
            url: 'https://my.domain.com/v1/customers/' + item.id,
            headers: {
                'Authorization': 'Bearer ' + token,
                'Accept': 'application/json'
            }
        }

        const buildArray = (await axios(config)).data
        list.push(JSON.parse(buildArray))
    }

    return list

} catch (err) {
    throw Error ('buildList error: ', err.message)
}
}
4
I am not sure about the line const buildArray = (await axios(config)).data but as per the result you have shared you can parse it and it works here codepen.io/Maniraj_Murugan/pen/LYGrPXW ..Maniraj Murugan
Please, have a look at my question, I have updated it. I did the same test like yours, I know that it works, but I don't understand why when I get data from Axios response it does not work.Taguada

4 Answers

0
votes

Is this OK?

const response = await axios(config) // waiting to response
const { data } = response // make sure we can get data
let toJSON = JSON.parse(data)
0
votes

I have a couple of things you can try.

  1. I'd recommend you clarify your naming conventions. If the buildArray variable is an array then it can't be parsed unless in a JSON format. I'm continuing assuming it's the response data object you showed.

  2. Try escaping the quotes inside the initial quotes. It would look like this:

    data: "{\"id\":\"test1\", \"cool\":\"test2\"}"

  3. Axios returns a promise. Try using it in Promise.then format rather than awaiting.

axios(config).then((response) => 
{ 
   JSON.parse(response); 
}).catch((err) => 
{
   console.log("Failed: " + err);
});

Let me know if none of these work. Good luck :)

0
votes

please make sure you are getting response data correctly. and if you return data as object at the backend side, you don't need to parse with JSON. JSON.parse is used for parsing string to JSON Pleas run this and check:

const buildArray = (await axios(config)).data;
console.log(buildArray );
0
votes

I finally have found a workaround, but I don't know why Axios response was giving me a correct output of data response in everywhere I was looking at, but for some reason there was a weird ? (question mark) at the beginning of string, I only realised that after coping output and pasted it into a JSON validation website.

Basically from Visual Studio output it was showing correctly, something like that.

data: '{"id":"test1", "cool":"test2"}'

But for some reason when I copied this output from Visual Studio and pasted it into JSON validation website it gave me this result. A weird ? (question mark)

data: '?{"id":"49f362ad

So I tried to find a JSON regex validation, after running many different regex, on of them gave an undefined result instead of ? (question mark), so I tried this one below and worked, but this is bizarro and I'm not a developer man to discuss it further, I'm just sending this answer in order to share this result :)

list.push(JSON.parse(buildArray.replace(/[^\\"]+/).replace('undefined', '{')))