简体   繁体   English

将字符串转换为有效的 json

[英]converting string to a valid json

I need to extract an object from a javascript file using node.js.我需要使用 node.js 从 javascript 文件中提取一个对象。 I am able to read the javascript file and also able to slice the string that i need to convert as the object.我能够读取 javascript 文件,也能够将需要转换为对象的字符串切片。 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.我只想要这个文件中的 person 对象,我可以使用切片运算符来实现这一点。 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.我尝试解析它,但它不是有效的 JSON。 I need help converting it into a valid object.我需要帮助将其转换为有效对象。

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.最好只运行文件,运行命令 AboutLocale,然后 JSON.stringify 将输出转换为有效的 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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