简体   繁体   中英

How to convert from text to JSON using NodeJS?

I want to convert a text file to JSON, but in a very particular way. My text file looks like this:

Data 1:
datapoint1-1 = 21
datapoint1-2 = 23
Data 2:
datapoint2-1 = 21
datapoint2-2 = 23
datapoint2-3 = 23

I want to create a JSON file that separates this data like this:

{
 {
 "Data": "1",
 "Datapoints": [
   {
    "datapoint1-1": "21",
    "datapoint1-2": "23"
   }
  ]
 },
 {
 "Data": "2",
 "Datapoints": [
  {
   "datapoint2-1": "21",
   "datapoint2-2": "23",
   "datapoint2-3": "23"
  }
 ]
 }
}

My first step has split the data into 2 arrays inside an array. The first array is Data 1 plus its data-points and the second is Data 2 plus its data-points.

Now I am stuck on how I can convert those arrays into the JSON format I want. Does anyone have an idea? or can direct me in the right direction for this?

Thanks,

Here is my solution

const input = `
  Data 1:
  datapoint1-1 = 21
  datapoint1-2 = 23
  Data 2:
  datapoint2-1 = 21
  datapoint2-2 = 23
  datapoint2-3 = 23
`

const array = input.split('\n').reverse()
const response = []
let template = {}
template['Datapoints'] = []
let switcher = false

array.map(arr => {
  // remove empty strings
  if (arr) {
    if (arr.includes('datapoint')) {
      const keyValue = arr.split(' = ')
      template.Datapoints.push({ [`${keyValue[0]}`]: keyValue[1] })
    } else {
      const keyValue = arr.split(' ')
      template.Datapoints.reverse()

      template[keyValue[0]] = keyValue[1].slice(0, -1)
      switcher = true
    }

    if (switcher) {
      response.push(template)
      template = {}
      template['Datapoints'] = []
      switcher = false
    }
  }
})

const finalResponse = response.reverse()

console.log(JSON.stringify(finalResponse, null, 2))

and in console you got

[
  {
    "Datapoints": [
      {
        "datapoint1-1": "21"
      },
      {
        "datapoint1-2": "23"
      }
    ],
    "Data": "1"
  },
  {
    "Datapoints": [
      {
        "datapoint2-1": "21"
      },
      {
        "datapoint2-2": "23"
      },
      {
        "datapoint2-3": "23"
      }
    ],
    "Data": "2"
  }
]

To convert text files in JSON you can use the JACKSON OBJECT MAPPER jar in your code. Create a simple POJO. It will read JSON string from a file and map it to your class. Then you would need to convert the JSON string value to java object. This will help you with the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM