restAPI- how to format JSON value

Viewed 70

I am getting JSON value from my server and it works well. But I want to customize my JSON value. I have two questions:

First, when I get region value, I get it like ["USA"],["Mexico"],["Canada"]. Is there a way I can ignore the double quotes/brackets and just get the strings values like USA, Mexico, Canada?

Second, when I get the regDate value I get the whole data like 2018-10-31T07:53:12.000Z instead, can I ignore some values and get it like 2018-10-31 07:53?

{
  "result": "ok",
  "data": [
      {
        "idx": 1,
        "region": "[\"USA \", \"Mexico \", \"Canada \"]",
        "regDate": "2018-10-31T07:53:12.000Z"
      }
   ]
}
2 Answers

Seems that your region data was double-encoded. In javascript, you'll want to decode that, e.g.

const response = {
  "result": "ok",
  "data": [
      {
        "idx": 1,
        "region": "[\"USA \", \"Mexico \", \"Canada \"]",
        "regDate": "2018-10-31T07:53:12.000Z"
      }
   ]
};

const regions = JSON.parse(response.data[0].region);

For time formatting, you could use the built-in Javascript Date type, such as..

const regDate = new Date(response.data[0].regDate);
const regDatestr = 
  regDate.getUTCFullYear() + '-' +
  regDate.getUTCMonth() + '-' +
  regDate.getDate() + ' ' +
  regDate.getUTCHours() + ':' +
  regDate.getUTCMinutes()
;

If you need more functionality than the built-in, I would recommend date-fns.

You'd save the results of your JSON query to a variable data. Then you'd do this:

var countries = "";

for (var i = 0; i < data[0].region.length; i++) {
    countries += data[0].region[i];
}

var time = data[0].regDate.split("000Z");
Related