NineCattoRules
NineCattoRules

Reputation: 2428

How to Parse Array of JSON Objects using Axios

Using Axios I'm trying to pass JSON data as params to the endpoint URL.

My params:

const annotations = {
    "key": "Book.pdf",
    "pages": [
      {
        "start": "12",
        "end": "20"
      },
      {
        "start": "35",
        "end": "40"
      }
    ]
}

My async function:

try {
    const result = await axios.get(endpoint, {
        params: annotations,
        paramsSerializer: params => parseParams(params),
        headers: {
            'Authorization': 'Bearer ' + jwtToken,
            'Content-Type': 'application/json'
        },
        'withCredentials': true
    });
} catch (error) {
    console.log(error);
}

Function to parse the URL (GitHub):

const parseParams = (params) => {
  const keys = Object.keys(params);
  let options = '';

  keys.forEach((key) => {
    const isParamTypeObject = typeof params[key] === 'object';
    const isParamTypeArray = isParamTypeObject && (params[key].length >= 0);

    if (!isParamTypeObject) {
      options += `${key}=${params[key]}&`;
    }

    if (isParamTypeObject && isParamTypeArray) {      
      params[key].forEach((element) => {
        options += `${key}=${element}&`;
      });
    }
  });

  return options ? options.slice(0, -1) : options;
};

The problem is that results in error 500:

https://api.mysite.com/ConvertBook?key=Book.pdf&regions=[object%20Object]&regions=[object%20Object]

I can't find a solution on the web, so how can I parse Array of JSON Objects in Axios?

Upvotes: 1

Views: 789

Answers (1)

Salketer
Salketer

Reputation: 15711

I'd use JSON.stringify on your params...

const parseParams = (params) => {
  const keys = Object.keys(params);
  let options = [];

  keys.forEach((key) => {
    options.push(`${key}=${encodeURIComponent(JSON.stringify(params[key]))}`);
  });

  return options.join('&');
};

Upvotes: 1

Related Questions