Manav jethani
Manav jethani

Reputation: 32

converting string to a valid json

I need to extract an object from a javascript file using node.js. I am able to read the javascript file and also able to slice the string that i need to convert as the object. Here is my code.

const AboutLocale = function() {
  return {
    person: {
      name: "zxczv",
      age: 25,
      gender: "male",
    },
    ar: true,
  };
};

I just want the person object from this file and i am able to achieve this using slice operator. Now it gives me a string that looks like this

  "{
    name: "man",
    age: 25,
    gender: "male",
  }"

I tried parsing it but it is not a valid JSON. I need help converting it into a valid object.

Upvotes: 0

Views: 375

Answers (1)

vityavv
vityavv

Reputation: 1490

You can do this with a bit of regex. The first one replaces all property names with themselves, but quoted. The second one removes any commas before a closing bracket. Note that this is a very fragile solution and might break if you throw anything unexpected at it. It's better just to run the file, run the command AboutLocale, and then JSON.stringify the output into valid JSON.

const input = `{
    name: "man",
    age: 25,
    gender: "male",
  }`

const input2 = `{header:"Aboutjdkahsfjk34",productShortName:"OBDX123456",version:"Version",servicePack:"Service Pack",poweredByValue:"asag",copyright:"Copyright 2006-2020",build:"Build",name:"manav"}`

const input3 = `{header:"Aboutjdka,hsfjk34",productShortName:"OBDX1,23456",version:"Version",servicePack:"Service Pack",poweredByValue:"asag",copyright:"Copyright 2006-2020",build:"Build",name:"manav"}`

fixed = input.replace(/\b(.*?):/g, "\"$1\":").replace(/,.*\n.*}/gm, "}")
fixed2 = input2.replace(/([,{])(.*?):/g, "$1\"$2\":")

let fixed3 = ""
let inAProperty = false
input3.split("").forEach((e,i) => {
  if (e === "{") fixed3 += "{\""
  else if (e === ":") fixed3 += "\":"
  else if (e === ",") fixed3 += inAProperty ? e : ",\""
  else if (e === "\"") {
    inAProperty = !inAProperty
    fixed3 += e
  } else fixed3 += e
})

console.log(fixed)
console.log(JSON.parse(fixed))

console.log(fixed2)
console.log(JSON.parse(fixed2))

console.log(fixed3)
console.log(JSON.parse(fixed3))

Upvotes: 1

Related Questions