Home > Blockchain >  Converting Key=Value text file to JSON
Converting Key=Value text file to JSON

Time:08-19

I'm looking for a library to convert a text file to JSON. Do you know which one has the following behavior? I already test some libraries but without success.

The source files contains a list of key=value pairs, one key per line. Converting to correct data type is important, my files has:

  • string keys
  • number keys
  • boolean keys
  • object (JSON) keys
  • arrays (of simple strings or of JSON objects)

Example

name = "test"
version = 3
enabled = true
fruit = {"type":"orange","color":"orange"}
consumers = ["kids", "adults"]
years = [2014, 2015]
fruits = [{"type":"orange","color":"orange"},{"type":"apples","method":"red"}]

Expected Result after conversion: Valid JSON (don't need style/identation)

{
  "name": "test",
  "version": 3,
  "enabled": true,
  "fruit": {
    "type": "orange",
    "color": "orange"
  },
  "consumers": [
    "kids",
    "adults"
  ],
  "years": [
    2014,
    2015
  ],
  "fruits": [
    {
      "type": "orange",
      "color": "orange"
    },
    {
      "type": "apples",
      "method": "red"
    }
  ]
}

CodePudding user response:

The format you're using isn't standardized so I'm doubtful you'll find a package that can parse it out of the box. Your values do look to be valid JSON primitives so you can leverage JSON.parse to parse the right hand side. With that you'd just need a parser to robustly pull out all the raw [key, value] pairs, but most parsers probably try to do more than just that which might not be what you want.

If you know the input will always be clean and don't need a completely robust parser, it's not difficult to roll this yourself:

const data = fs.readFileSync('./data.txt', {encoding: 'utf8'}).split('\n').filter(Boolean)
const obj = {}
for (const line of data) {
    const [key, val] = line.split(/\s*=\s*(. )/)
    obj[key] = JSON.parse(val)
}
  • Related