PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 14, 2022

[FIXED] How to Parse Array of JSON Objects using Axios

 October 14, 2022     axios, javascript     No comments   

Issue

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?


Solution

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('&');
};


Answered By - Salketer
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing