0

I'm attempting to use Axios to GET some data from a backend. The data is usually returned in MessagePack form, but Axios auto-parses the data into what I believe is JSON. However, the response data appears to have a "%" sign in front of every entry and the key values are not all surrounded by quotes. Proper JSON format requires even the key to be in quotes to signify that it is a string. I'm not able to change the backend or what data form I get after making the call. I'm trying to access the data inside but it returns undefined. Trying to parse the JSON string also gets me nowhere; it stops at the first character "%" and says "Unexpected token".

%{ attendance: nil, away_team: %{ age_group: nil, id: 3222, main_color: [2, 1, 4], name: "Random Name", national: false, region: %{id: 11, name: "Country"}, sex: "male" }

shaotime
  • 39
  • 1
  • 3

2 Answers2

1

In Axios you can specify the response type as arraybuffer, blob, document, json, text, stream. Text should do the trick. Documentation is here

responseType: 'text', 
SamCodeBad
  • 231
  • 5
  • 10
0

You can use interceptors to format the returned data from server before using it. I assume that, as you said, server returns data with a prefix % on every new open brackets:

const WEBSERVER_ENDPOINT = 'www.whatever.it/api'
let instance = axios.create({
    baseURL: WEBSERVER_ENDPOINT,
});

// response instanceof AxiosResponse
instance.interceptors.response.use(async function (response) {
    let dataLikeJson = response.data.replace(/%{/g, '{'); //  replace all '%{' with '{' 
    response.data = JSON.parse(dataLikeJson); //then parse it in JSON

    return response;
}, function (error) {
   // Do something with request error
   return Promise.reject(error);
});

// blabla the rest...
instance.post(...)

Here is the documentation https://github.com/axios/axios#interceptors

EDIT: For what I understood, the known format '{key: "value"}' is called relaxed-json. There are some discussions about parsing this kind of json.

jrumandal
  • 115
  • 1
  • 10
  • Hi! The % signs are replaced, but the problem remains that the response keys still don't have quotation marks around them. When JSON.parse gets called on it, I still get an unexpected token on the data it is trying to parse. – shaotime Feb 25 '19 at 14:07
  • Hi, for what i understood, the bad formatted json is called relaxed-json. I will edit my answer and paste the link. – jrumandal Feb 28 '19 at 10:06