1

Hello I'm consuming data from an API using Axios, the problem is that this data is in csv format and I'm trying to convert it to a JSON object.

I tried to use some js libraries but none of them worked with Vue

What can I do?

Example:

(This how the data is represented)

fecha,casos_total,casos_pcr,casos_test_ac,altas,fallecimientos,ingresos_uci,hospitalizados
2020-02-21,3,3,,,,,
2020-02-22,3,3,,,,,
2020-02-23,3,3,,,,,
2020-02-24,3,3,,,,,
2020-02-25,4,4,,,,,

(This is how I want to be displayed)

[
  {
    "fecha": "2020-02-21",
    "casos_total": 3,
    "casos_pcr": 3,
    "casos_test_ac": "",
    "altas": "",
    "fallecimientos": "",
    "ingresos_uci": "",
    "hospitalizados": ""
  },
  {
    "fecha": "2020-02-22",
    "casos_total": 3,
    "casos_pcr": 3,
    "casos_test_ac": "",
    "altas": "",
    "fallecimientos": "",
    "ingresos_uci": "",
    "hospitalizados": ""
  },
  {
    "fecha": "2020-02-23",
    "casos_total": 3,
    "casos_pcr": 3,
    "casos_test_ac": "",
    "altas": "",
    "fallecimientos": "",
    "ingresos_uci": "",
    "hospitalizados": ""
  },
  {
    "fecha": "2020-02-24",
    "casos_total": 3,
    "casos_pcr": 3,
    "casos_test_ac": "",
    "altas": "",
    "fallecimientos": "",
    "ingresos_uci": "",
    "hospitalizados": ""
  },
  {
    "fecha": "2020-02-25",
    "casos_total": 4,
    "casos_pcr": 4,
    "casos_test_ac": "",
    "altas": "",
    "fallecimientos": "",
    "ingresos_uci": "",
    "hospitalizados": ""
  }
]

Thanks!

1 Answer 1

3
  1. Split the input string by \n to get the individual lines.

  2. Split the first line by , to get the headers.

  3. Split the following lines by , to get the fields.

  4. Join the headers and fields by index (map the headers into an array of header name and field name), and create an object from the result.

const input = `fecha,casos_total,casos_pcr,casos_test_ac,altas,fallecimientos,ingresos_uci,hospitalizados
2020-02-21,3,3,,,,,
2020-02-22,3,3,,,,,
2020-02-23,3,3,,,,,
2020-02-24,3,3,,,,,
2020-02-25,4,4,,,,,`

const lines = input.split('\n') // 1️⃣
const header = lines[0].split(',') // 2️⃣
const output = lines.slice(1).map(line => {
  const fields = line.split(',') // 3️⃣
  return Object.fromEntries(header.map((h, i) => [h, fields[i]])) // 4️⃣
})

console.log(output)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.