nodejs - convert json string to valid json data

Viewed 37

I use nodejs/knex.js that connects to oracle database 11.2. SQL returns the below as json string(varchar2).

{
"empData" :
'[{"salary": 1000, "emp": 4500, "hire data": "15-SEP-04"},
  {"salary": 1000, "emp": 1405, "hire data": "10-JAN-08"},
  {"salary": 1000, "emp": 2651, "hire data": "19-SEP-05"}]'
}

But, I want convert it as below (valid JSON)

{
   "empData":[
      {
         "salary":1000,
         "emp":4500,
         "hire data":"15-SEP-04"
      },
      {
         "salary":1000,
         "emp":1405,
         "hire data":"10-JAN-08"
      },
      {
         "salary":1000,
         "emp":2651,
         "hire data":"19-SEP-05"
      }
   ]
}

I tried all the JSON.parse(), JSON.stringify(), eval(). empData array comes as one string.

Any thoughts?

Thanks for your help!

2 Answers

You need to do few tweaks, try the below snippet:

customJsonParser = (semiJsonString) => {
    if (typeof semiJsonString === 'string') {
        // to throw an error if the string is not valid JSON
        try {
            return JSON.parse(semiJsonString);
        } catch (e) {
            return semiJsonString
        }
    }

    return Object
        .fromEntries(Object
            .entries(semiJsonString)
            .map(([key, value]) => [key, customJsonParser(value)])
        );
}

const input = `{
"empData" :
'[{"salary": 1000, "emp": 4500, "hire data": "15-SEP-04"},
  {"salary": 1000, "emp": 1405, "hire data": "10-JAN-08"},
  {"salary": 1000, "emp": 2651, "hire data": "19-SEP-05"}]'
}`;

console.log(customJsonParser(input));

I'm not the best at explaining things, and this can be optimized but I have minimal time before I need to go. Here's my way around this issue:

I've edited this as, well.. it was too complex.

const data = {
    "empData" : '[{"salary": 1000, "emp": 4500, "hire data": "15-SEP-04"},{"salary": 1000, "emp": 1405, "hire data": "10-JAN-08"},{"salary": 1000, "emp": 2651, "hire data": "19-SEP-05"}]'
}

function parseData(name, dataInput) {
    dataInput[name] = JSON.parse(dataInput[name])

    return dataInput
}

console.log(parseData("empData",data));
Related